C++ multimap::cbegin() 函数



C++ 的 std::multimap::cbegin() 函数用于返回指向 multimap 中第一个元素的常量迭代器,从而可以只读访问其元素。与返回可变迭代器的 begin() 函数不同,cbegin() 函数确保数据无法修改,从而提高了对其元素进行安全迭代的效率。该函数的时间复杂度为常数,即 O(1)。

语法

以下是 std::multimap::cbegin() 函数的语法。

const_iterator cbegin() const noexcept;

参数

此函数不接受任何参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

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

示例

让我们看下面的例子,我们将使用 cbegin() 函数并访问第一个元素。

Open Compiler
#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() 函数查找特定元素。

Open Compiler
#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。

Open Compiler
#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
广告