C++ STL 中 map crbegin() 和 crend() 函数
在本文中,我们将讨论 C++ STL 中 map::crbegin() 和 map::crend() 函数的工作原理、语法和示例。
什么是 C++ STL 中的 Map?
Map 是关联容器,它可以方便地存储由键值对组成的元素,并按特定顺序排列。在 map 容器中,数据内部总是根据其关联的键进行排序。map 容器中的值可以通过其唯一的键进行访问。
什么是 map::cbegin()?
map::crbegin() 函数是 C++ STL 中的内置函数,它在
语法
Map_name.crbegin();
参数
此函数不接受任何参数。
返回值
此函数返回一个迭代器,指向 map 容器的最后一个元素。
示例
输入
map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3; newmap.crbegin();
输出
c:3
map::crbegin
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({3, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
//using map::crbegin to fetch first last element
auto temp = TP_Map.crbegin();
cout<<"First element is: "<<temp->first << " -> " << temp->second;
cout<<"\nTP Map is : \n";
cout << "MAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.crbegin(); i!= TP_Map.crend(); i++) {
cout << i->first << "\t" << i->second << endl;
}
return 0;
}输出
First element is: 4 -> 70 TP Map is: MAP_KEY MAP_ELEMENT 4 70 3 50 2 30 1 10
什么是 map::crend()?
map::crend() 函数是 C++ STL 中的内置函数,它在 `
语法
newmap.crend();
参数
此函数不接受任何参数。
返回值
它返回一个迭代器,指向关联的 map 容器的第一个元素之前的位置。
示例
输入
map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3; newmap.crend();
输出
error
map::crend
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({3, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
cout<<"\nTP Map is : \n";
cout << "MAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.crbegin(); i!= TP_Map.crend(); i++) {
cout << i->first << "\t" << i->second << endl;
}
return 0;
}输出
TP Map is: MAP_KEY MAP_ELEMENT 4 70 3 50 2 30 1 10
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP