关联容器的操作(pair,map)
示例代码:
#include <map>
#include <iostream>
#include <string>
#include <algorithm>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int main()
{
string name="jack";
pair<int,string> pair1(1,name);
pair<int,string> pair2(2,"老张");
map<int,string> map1;
map1.insert(pair1);
map1.insert(pair2);
cout<<"通过find函数返回的迭代器访问键值为1的关联条目"<<endl;
auto it = map1.find(1);
if(it!=map1.end())
{
string name = it ->second;
std::cout << name << endl;
}
std::cout << "访问键值为2的关联条目" << endl;
std::cout << "名字" << map1[2]<<endl;
std::cout << "删除键值为2的pair" << endl;
map1.erase(2);
std::cout << "访问键值为2的关联条目" << endl;
std::cout << "名字:" << map1[2] << endl;
return 0;
}
pair<int,string> pair1(1,name);
pair<int,string> pair2(2,"老张");
map<int,string> map1;
map1.insert(pair1);
map1.insert(pair2);
cout<<"通过find函数返回的迭代器访问键值为1的关联条目"<<endl;
auto it = map1.find(1);
if(it!=map1.end())
{
string name = it ->second;
std::cout << name << endl;
}
std::cout << "访问键值为2的关联条目" << endl;
std::cout << "名字" << map1[2]<<endl;
std::cout << "删除键值为2的pair" << endl;
map1.erase(2);
std::cout << "访问键值为2的关联条目" << endl;
std::cout << "名字:" << map1[2] << endl;
return 0;
}
结果:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步