C++ multimap::cbegin() 函式



C++ 的 std::multimap::cbegin() 函式用於返回指向 multimap 中第一個元素的常量迭代器,從而可以只讀訪問其元素。與返回可變迭代器的 begin() 函式不同,cbegin() 函式確保資料無法修改,從而提高了對其元素進行安全迭代的效率。該函式的時間複雜度為常數,即 O(1)。

語法

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

const_iterator cbegin() const noexcept;

引數

此函式不接受任何引數。

返回值

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

示例

讓我們看下面的例子,我們將使用 cbegin() 函式並訪問第一個元素。

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

輸出

以上程式碼的輸出如下:

1: Welcome

示例

考慮以下示例,我們將使用 cbegin() 函式查詢特定元素。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "Hi"}, {2, "Hello"}, {3, "Namaste"}};
    auto x = a.cbegin();
    while (x != a.cend() && x->first != 3) {
        ++x;
    }
    if (x != a.cend()) {
        std::cout << "Element found: " << x->second << std::endl;
    } else {
        std::cout << "Element not found." << std::endl;
    }
    return 0;
}

輸出

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

Element found: Namaste

示例

在以下示例中,我們將使用 cbegin() 函式遍歷 multimap。

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

輸出

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

1: TutorialsPoint
2: TP
3: Tutorix
multimap.htm
廣告