下面代码主要演示了map初始化,插入,插入成功与否判断,遍历map,修改map值等操作。
#include <map>
#include <iostream>
#include <string>
using namespace std;
struct cmp
{
bool operator()(pair<int,string> p, pair<int,string> q)
{
return p.first > q.first;
}
};
int main()
{
//unordered_map<int, string> map = {{1,"qaz"},{2,"qwe"}};
map<int, string > map = {{1,"qaz"},{2,"qwe"}};
// three method to insert
map[1] = "abc"; //value modify
//pair< map<int, string>::iterator, bool> it1 = map.insert({2,"def"});
auto it = map.insert({2,"def"});//insert failed because 2 has existed
if(it1.second == false)
{
std::cout<<"map的key里面已经有2了! 插入失败"<<std::endl;
}
else {
cout << "插入2成功";
}
map.insert(pair<int, string>(3, "ghi"));
//visit ele method 1
for(auto it = map.begin(); it!= map.end(); it++)
{
std::cout<<it->first<<" "<<it->second<<std::endl;
}
//visit ele method 1
for(auto &&[key,value] : map)
{
std::cout<<key<<" "<<value.c_str()<<std::endl;
}
//modify value
for(auto &[key,value] : map)
{
value = "def";
std::cout<<key<<" "<<value.c_str()<<std::endl;
}
return 0;
}
本文通过代码示例详细讲解了C++标准模板库中的map如何进行初始化、插入元素、检查插入状态、遍历以及修改元素值等基本操作,是理解C++ map数据结构实用性的实战指南。
1万+

被折叠的 条评论
为什么被折叠?



