map/multimap
阿新 • • 發佈:2020-08-15
map/multimap
1.特性
map保證出現在map內的pair只出現一次,且map內的元素按照first從小到大排序,但是當first相同時,那麼按照輸入的順序排序
2.初始化
①初始化一個對映
map<int, int> m;
②複製一個對映
map <int ,int > mm(m);
3.求長度(時間複雜度為O(1))
m.size();
4.判空(時間複雜度為O(1))
a.empty();
5.清空
a.clear();
6.刪除元素/插入元素
a.erase(1); // 刪除first為1的那個值 ,時間複雜度為O(logn ) a.erase(a.begin()); // 刪除map的第一個元素 a.insert({1, 2}); // 插入一個pair a[1] = 2; // 插入一個pair,時間複雜度為O(logn)
7.判斷一個數是否出現過
a.count(x); // 判斷x是否在集合中出現過,如果出現過返回1,否則0
8.迭代器
a.begin(); // 第一個元素的迭代器
a.end(); // 最後一個元素的下一位的迭代器
9.遍歷
// 1.迭代器遍歷 for (map<int,int>::iterator it = m.begin(); it != m.end(); ++it) cout << (*it).second << ends; // 2. c++方式遍歷 for (auto mi: m) cout << mi.second << ends;
10.查詢(支援lower_bound() 和 upper_bound()操作)
map<int, int> s;
s[1] = 2;
S[2] = 3;
map <int> ::iterator it = m.lower_bound(2);
if (it != m.end()) cout << *it;
else cout << 0;
11.multimap的性質和map一樣,上面全是map的特性,而multimap在map的特性之上使得一個集合內可以出現多次同一個元素,multimap內的元素也是按照字典序排好序的
multimap<int, int> m; m.insert({1, 2}); m.insert({1, 3}); for (auto mi: m) cout << mi.second << ends;
輸出
2 3
在s.erase(int x)時,會刪除所有出現的x,時間複雜度為O(logn + k) (k為出現次數)
multimap<int, int> m;
m.insert({1, 4});
m.insert({1, 3});
m.insert({1, 5});
m.erase(1);
cout << m.empty();
輸出
1