C++ multimap::begin() 函式



C++ 的std::multimap::begin()函式是一個標準容器,它儲存鍵值對,允許具有相同鍵的多個條目。它用於返回指向容器中第一個元素的迭代器。如果 multimap 為空,begin() 函式返回與 end() 相同的迭代器。此函式的時間複雜度為常數,即 O(1)。

begin() 函式與其他迭代器一起使用以訪問或操作 multimap 中的元素。

語法

以下是 std::multimap::begin() 函式的語法。

iterator begin();
const_iterator begin() const;

引數

此函式不接受任何引數。

返回值

此函式返回一個指向第一個元素的迭代器。

示例

讓我們來看下面的例子,我們將演示 begin() 函式的用法。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "TutorialsPoint"}, {2, "TP"}, {3, "Tutorix"}};
    auto it = a.begin();
    std::cout << it->first << ": " << it->second << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

1: TutorialsPoint

示例

考慮下面的例子,我們將使用 for 迴圈迭代 multimap 中從 begin() 指向的元素開始到 end() 結束的所有元素。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "Hello"}, {2, "Namaste"}, {1, "Vanakam"}};
    for(auto it = a.begin(); it != a.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }
    return 0;
}

輸出

以下是以上程式碼的輸出:

1: Hello
1: Vanakam
2: Namaste

示例

在下面的示例中,我們將使用 begin() 獲得的迭代器修改 multimap 中第一個元素的值。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "Benz"}, {2, "Audi"}, {3, "Ciaz"}};
    auto it = a.begin();
    it->second = "Cruze";
    for(const auto& p : a) {
        std::cout << p.first << ": " << p.second << std::endl;
    }
    return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

1: Cruze
2: Audi
3: Ciaz

示例

下面的示例將檢查 multimap 是否為空。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    if(a.begin() == a.end()) {
        std::cout << "Multimap is empty." << std::endl;
    } else {
        std::cout << "Multimap is not empty." << std::endl;
    }
    return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Multimap is empty.
multimap.htm
廣告