map 倒序遍历 reverse_iterator
作者:
xianhai
,
2022-02-12 15:05:21
,
所有人可见
,
阅读 388
#include <iostream>
#include <map>
using namespace std;
map<int, int> mp;
int main() {
mp[50] = 2;
mp[30] = 6;
mp[10] = 1;
cout << mp.size() << endl;
// 遍历
for (auto [k, v] : mp) {
cout << k << ' ' << v << endl;
}
// 迭代
cout << "iterator: " << endl;
for (map<int, int>::iterator it = mp.begin(); it != mp.end(); it++) {
cout << (*it).first << "," << (*it).second << endl;
}
for (auto it = mp.begin(); it != mp.end(); it++) {
cout << (*it).first << "," << (*it).second << endl;
}
// 倒序遍历 map<int, int>::reverse_iterator
cout << "reverse_iterator:" << endl;
for (map<int, int>::reverse_iterator rit = mp.rbegin(); rit != mp.rend(); rit++) {
cout << (*rit).first << "," << (*rit).second << endl;
}
cout << "倒序遍历:" << endl;
for (auto rit = mp.rbegin(); rit != mp.rend(); rit++) {
cout << (*rit).first << "," << (*rit).second << endl;
}
return 0;
}
unordered_map的底层实现是哈希表,查找的时间复杂度为O(1)
map的底层实现是红黑树,查找的时间复杂度为O(logn)