C++中map的常用操作如下:
int main() {
map<char, int> cnt;
string str = "abcdef";
// map 中添加元素
for(auto c : str) cnt[c] ++;
// 遍历map
for(auto c : cnt) cout << c.first << " " << c.second << endl;
cout << "==============================================" << endl;
// find函数,根据 map 中的 key 进行获取value值
cout << cnt.find('a') ->first << " " << cnt.find('a') ->second << endl;
cout << "==============================================" << endl;
// 根据 key 进行元素的删除
cnt.erase('a');
for(auto c : cnt) cout << c.first << " " << c.second << endl;
cout << "==============================================" << endl;
// 向 map 中插入元素
cnt.insert(make_pair('g', 1));
for(auto c : cnt) cout << c.first << " " << c.second << endl;
// 获取 map 集合的大小和判断集合是否为空
cout << cnt.size() << " " << cnt.empty() << endl;
return 0;
}
以上代码的运行结果如下所示: