首页 文章资讯内容详情

C ++ STL中的multimap :: cbegin()和multimap :: cend()

2026-06-05 1 花语

在本文中,我们将讨论C++STL中multimap::cbegin()和multimap::cend()函数的工作原理,语法和示例。

什么是C++STL中的Multimap?

多图是关联容器,类似于图容器。它还有助于按特定顺序存储由键值和映射值的组合形成的元素。在多图容器中,可以有多个与同一键关联的元素。始终在内部借助关联的键对数据进行排序。

什么是multimap::cbegin()?

multimap::cbegin()函数是C++STL中的内置函数,在<map>头文件中定义。cbegin()是常量开始函数。此函数返回常量迭代器,该迭代器指向multimap容器中的第一个元素。返回的迭代器是常量迭代器,它们不能用于修改内容。我们可以通过增加或减少迭代器来使用它们在映射容器的各个元素之间进行遍历。

语法

multi.cbegin();

参数

此函数不接受任何参数。

返回值

它返回一个指向关联映射容器第一个元素的迭代器。

输入值

multimap<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3; newmap.cbegin();

输出-

a = 1

示例

#include <bits/stdc++.h> using namespace std; int main(){ //create the container multimap<int, int> mul; //insert using emplace mul.emplace_hint(mul.begin(), 1, 10); mul.emplace_hint(mul.begin(), 2, 20); mul.emplace_hint(mul.begin(), 2, 30); mul.emplace_hint(mul.begin(), 1, 40); mul.emplace_hint(mul.begin(), 1, 50); mul.emplace_hint(mul.begin(), 5, 60); auto it = mul.cbegin(); cout << "First element in the multimap is: "; cout << "{" << it->first << ", " << it->second << "}\n"; cout << "\nElements in multimap is : \n"; cout << "KEY\tELEMENT\n"; for (auto i = mul.cbegin(); i!= mul.cend(); i++){ cout << i->first << "\t" << i->second << endl; } return 0; }

输出结果

如果我们运行上面的代码,它将生成以下输出-

First element in the multimap is: {1, 50} Elements in multimap is : KEY ELEMENT 1 50 1 40 1 10 2 30 2 20 5 60

什么是multimap::cend()?

multimap::cend()函数是C++STL中的内置函数,在<map>头文件中定义。cend()函数是常量end()。此函数返回元素的常量迭代器,该迭代器位于关联的multimap容器中的最后一个元素之后。

返回的迭代器是常量迭代器,不能用于修改内容。通过增加或减少迭代器,我们可以使用它们遍历映射容器的元素。

multimap::cbegin()和multimap::cend()用于通过给出范围的起点和终点来遍历整个容器。

语法

multi.cend();

参数

此函数不接受任何参数。

返回值

它返回一个迭代器,该迭代器指向关联的映射容器的最后一个元素。

输入-

multimap <char, int> newmap; newmap(make_pair(‘a’, 1)); newmap(make_pair(‘b’, 2)); newmap(make_pair(‘c’, 3)); newmap.cend();

输出-

error

示例

#include <bits/stdc++.h> using namespace std; int main(){ //create the container multimap<int, int> mul; //insert using emplace mul.emplace_hint(mul.begin(), 1, 10); mul.emplace_hint(mul.begin(), 2, 20); mul.emplace_hint(mul.begin(), 2, 30); mul.emplace_hint(mul.begin(), 1, 40); mul.emplace_hint(mul.begin(), 1, 50); mul.emplace_hint(mul.begin(), 5, 60); cout << "\nElements in multimap is : \n"; cout << "KEY\tELEMENT\n"; for (auto i = mul.cbegin(); i!= mul.cend(); i++){ cout << i->first << "\t" << i->second << endl; } return 0; }

输出结果

如果我们运行上面的代码,它将生成以下输出-

Elements in multimap is : KEY ELEMENT 1 50 1 40 1 10 2 30 2 20 5 60