C++ multimap::begin() 函数



C++ 的std::multimap::begin()函数是一个标准容器,它存储键值对,允许具有相同键的多个条目。它用于返回指向容器中第一个元素的迭代器。如果 multimap 为空,begin() 函数返回与 end() 相同的迭代器。此函数的时间复杂度为常数,即 O(1)。

begin() 函数与其他迭代器一起使用以访问或操作 multimap 中的元素。

语法

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

iterator begin(); const_iterator begin() const;

参数

此函数不接受任何参数。

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

返回值

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

示例

让我们来看下面的例子,我们将演示 begin() 函数的用法。

Open Compiler
#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() 结束的所有元素。

Open Compiler
#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 中第一个元素的值。

Open Compiler
#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 是否为空。

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