C++ STL 中的 multimap::crbegin() 和 multimap::crend()


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

什么是 C++ STL 中的 Multimap?

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

什么是 multimap::cbegin()?

multimap::crbegin() 函数是 C++ STL 中的内置函数,它在 <map> 头文件中定义。crbegin() 代表常量反向开头,意味着它是 cbegin(常量开头)的反向,换句话说,crbegin() 函数将返回指向与该函数关联的 multimap 容器的最后一个元素的迭代器。此迭代器不能用于修改 multimap。它只能用于遍历集合容器。

语法

mutliMap_name.crbegin();

参数

此函数不接受任何参数。

返回值

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

输入

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

输出

c:3

示例

在线演示

#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.crbegin();
   cout<<"Last element using crbegin() is: {"<<it->first<< ", " << it->second << "}\n";
   cout <<"\nElements in multimap is : \n";
   cout << "KEY\tELEMENT\n";
   for (auto i = mul.crbegin(); i!= mul.crend(); i++){
      cout << i->first << "\t" << i->second << endl;
   }
   return 0;
}

输出

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

Last element using crbegin() is: {5, 60}
Elements in multimap is :
KEY ELEMENT
5 60
2 20
2 30
1 10
1 40
1 50

什么是 multimap::crend()?

multimap::crend() 函数是 C++ STL 中的内置函数,它在 <map> 头文件中定义。crend() 代表常量反向结束迭代器,意味着它是 cend(常量结束迭代器)的反向,换句话说,crend() 函数将返回指向与该函数关联的容器的第一个位置之前的迭代器。此迭代器不能用于修改 multimap。它只能用于遍历 multimap 容器。

语法

newmultimap.crend();

参数

此函数不接受任何参数。

返回值

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

输入

multimap<char, int&lgt; newmap;
newmap(make_pair(‘a’, 1));
newmap(make_pair(‘b’, 2));
newmap(make_pair(‘c’, 3));
newmap.crend();

输出

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.crbegin(); i!= mul.crend(); i++){
      cout <<<; i->first << "\t" << i->second < endl;
   }
   return 0;
}

输出

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

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

更新于:2020年4月22日

94 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.