map
构造
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include <iostream> #include <map>
using namespace std;
int main() { map<int, string> m1;
map<int, string> m2 = {{1, "one"}, {2, "two"}, {3, "three"}};
map<int, string> m3(m2);
map<int, string> m4(m2.begin(), m2.end());
return 0; }
|
api
基本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include <iostream> #include <map>
using namespace std;
int main() { map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}};
m2.insert(pair<int, int>(4, 4)); m2.insert(make_pair(5, 5));
cout << "当前容量: " << m2.size() << endl;
cout << m2[1] << endl; cout << m2[2] << endl; cout << m2[3] << endl; cout << m2[4] << endl; cout << m2[5] << endl; cout << m2[6] << endl;
cout << "当前容量: " << m2.size() << endl;
cout << m2.at(6) << endl;
m2.erase(6);
auto it = m2.find(3); if (it != m2.end()) { cout << "find查找存在,key为:" << it->first << ",value为:" << it->second << endl; } else { cout << "find查找不存在" << endl; }
if (m2.count(3)) { cout << "m2.count(3)查找存在" << endl; } return 0; }
|
遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <iostream> #include <map>
using namespace std;
int main() { map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}};
for (auto &item : m2) { cout << item.first << " " << item.second << endl; } cout << endl;
for (auto it = m2.begin(); it != m2.end(); it++) { cout << it->first << " " << it->second << endl; } return 0; }
|
排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <iostream> #include <map> using namespace std;
struct CustomCompare { bool operator()(int a, int b) const { return a > b; } };
int main() { map<int, int, CustomCompare> m = {{1, 10}, {2, 20}, {3, 30}};
for (const auto& pair : m) { cout << pair.first << ": " << pair.second << endl; } return 0; }
|
并发修改
问题依旧在,参考vector和list,it也不能运算。下方是正确方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <iostream> #include <map>
using namespace std;
int main() { map<int, int> m2 = {{1, 1}, {2, 1}, {3, 1}, {4, 2}};
for (auto it = m2.begin(); it != m2.end();) { if (it->second == 1) { it = m2.erase(it); } else { ++it; } } return 0; }
|
底层原理
红黑树