3.map中的函数
(1)find()
m.find(key);
返回值为key
的映射的迭代器,时间复杂度是O(logN),N为map
中映射的个数
#include <iostream> #include <map> using namespace std; int main() { map<char, int> m; m['c'] = 3; m['a'] = 1; m['b'] = 2; map<char, int>::iterator it = m.find('b'); cout << it -> first << ' ' << it -> second << endl; return 0; }
输出结果为:b 2
(2)erase()
删除单个元素
m.erase(it);
,it
为需要删除元素的迭代器,时间复杂度为O(1)
#include <iostream> #include <map> using namespace std; int main() { map<char, int> m; m['c'] = 3; m['a'] = 1; m['b'] = 2; map<char, int>::iterator it = m.find('b'); m.erase(it); //删除 b 2 for (auto it = m.begin(); it != m.end(); it ++ ) cout << it -> first << ' ' << it -> second << endl; return 0; }
输出结果为:
a 1
c 3
m.erase(key);
,key
为欲删除的映射的键,时间复杂度为O(logN),N为map
内元素的个数
#include <iostream> #include <map> using namespace std; int main() { map<char, int> m; m['c'] = 3; m['a'] = 1; m['b'] = 2; m.erase(m.find('b')); //删除 b 2 for (auto it = m.begin(); it != m.end(); it ++ ) cout << it -> first << ' ' << it -> second << endl; return 0; }
删除一个区间内的所有元素
m.erase(first, last);
,其中first
是需要删除区间的起始迭代器,last
为需要删除的区间的末尾迭代器的下一个地址,即删除左闭右开区间[first, last)
,时间复杂度为O(last - first)
#include <iostream> #include <map> using namespace std; int main() { map<char, int> m; m['c'] = 3; m['a'] = 1; m['b'] = 2; m.erase(m.find('b'), m.end()); for (auto it = m.begin(); it != m.end(); it ++ ) cout << it -> first << ' ' << it -> second << endl; return 0; }
输出结果为:a 1
(3)size()
m.size()
用来获得map
中映射的对数,时间复杂度为O(1)
#include <iostream> #include <map> using namespace std; int main() { map<char, int> m; m['c'] = 3; m['a'] = 1; m['b'] = 2; cout << m.size(); return 0; }
输出结果为:3
(4)clear()
m.clear();
用来清空map
中的所有元素,时间复杂度为O(N),N为map
中元素的个数
#include <iostream> #include <map> using namespace std; int main() { map<char, int> m; m['c'] = 3; m['a'] = 1; m['b'] = 2; m.clear(); cout << m.size(); return 0; }
输出结果为:0