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


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

什么是 C++ STL 中的 Multimap?

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

什么是 multimap::cbegin()?

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

语法

multi.cbegin();

参数

此函数不接受任何参数。

返回值

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

输入

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() 函数是常量结束 ()。此函数返回关联的 multimap 容器中最后一个元素之后的元素的常量迭代器。

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

multimap::cbegin() 和 multimap::cend() 用于通过提供范围的开始和结束来遍历整个容器。

语法

multi.cend();

参数

此函数不接受任何参数。

返回值

它返回一个指向关联的 map 容器中最后一个元素之后的迭代器。

**输入** -

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

更新于: 2020-04-22

94 次浏览

启动您的 职业生涯

通过完成课程获得认证

立即开始
广告
© . All rights reserved.