示例代码:
#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;
}
结果: