map和pair的使用
pair参考网站: https://blog.csdn.net/sevenjoin/article/details/81937695
map参考网站: https://www.cnblogs.com/omelet/p/6617362.html
代码实现
#include <iostream>
#include <string>
#include <map> //运用map
#include <utility> //运用pair
using namespace std;
int main() {
map<string, int> mp1;
pair<string, int> pr1("abc", 3);
mp1.insert(pr1); //以pair形式添加
mp1[string("def")] = 6; //最基础的添加方式
mp1.erase(string("abc")); //根据键值删除
map<string, int>::iterator iter = mp1.begin();
mp1.erase(iter); //运用迭代器删除
map<string, int>::iterator iter; //运用迭代器遍历
for (iter = mp1.begin(); iter != mp1.end(); iter++)
cout << iter->first << endl << iter->second << endl; //first指向键值 second指向实值
if (mp1.find(string("def")) != mp1.end()) cout << "Yes" << endl; //查找
mp1[string("def")] = 9;
cout << mp1[string("def")] << endl; //基本赋值于输出
string name = "yyy";
int age = 19;
tie(name, age) = pr1; //将pair的键值和实值赋给各自类型的变量
cout << name << endl << age << endl;
pr1 = make_pair(name, age); //将组合类型赋给pair
cout << pr1.first << endl << pr1.second << endl; //用'.'指向键值和实值
return 0;
}