C++ map的使用
1. 序言
资料来源: c++参考手册.
2. 初始化
使用前要引入包含map的头文件
#include <map> //注意,STL头文件没有扩展名.h
通常使用以下代码进行map的初始化
map<int,int> map;
3. 修改
3.1 插入 insert()
1.插入一个元素,注意要包含{key, value}
map<int, int> map;
map.insert({2,2});
注: 插入时如存在该key值,则忽略此次插入
3.2 插入 insert_or_assign
插入时如存在key值则插入默认值
3.3 删除 erase
- void erase( iterator pos );
map<int,int> map;
map.insert({1,2});
map.erase(map.find(1)); // 删除map中的{1,2}
4. 查询
4.1 遍历
map<int,int> m;
map<int,int>::iterator iter;
iter = m.begin();
while(iter != m.end()){
cout << iter->first << "-" << iter->second << endl;
iter++;
}
for (iter = m.begin();iter != m.end(); iter++){
cout << iter->first << "-" << iter->second << endl;
}
for(auto &it : m){
cout << it.first << "-" << it.second <<endl;
}
4.2 是否存在 int count(const key& key)
查找map中存在key值元素的个数,因map中不存在重复元素,故如存在,返回1,不存在返回 0
map<int,int> map;
map.insert({2,2});
int a = map.count(2); // a = 1;
int b = map.count(3); // b = 0;
## 4.3
4.3 查找 iterator find( const Key& key );
返回所查询的key值元素的所在的迭代器
std::map<int,char> example = {{1,‘a’},{2,‘b’}};
auto search = example.find(2);
if (search != example.end()) {
std::cout << "Found " << search->first << " " << search->second << '\n';
} else {
std::cout << "Not found\n";
}
// 输出 Found 2 b