#include<iostream>
#include<map>
#include<unordered_map>
#include<algorithm>
#include<string>
using namespace std;
bool cmp(pair<int, string> a, pair<int, string> b) {
return a.first < b.first;
}
int main()
{
//构造
map<int, string> m;
//插入数据
//前三种方法当出现重复键时,编译器会报错,而第四种方法,当出现重复键时,会覆盖之前的键值对。
//1、pair
m.insert(pair<int, string>(2, "zhangsan"));
//2、make_pair
m.insert(make_pair<int, string>(8, "lisi"));
//3、value_type
m.insert(map<int, string>::value_type(6, "wangwu"));
//4、[]
m[9] = "pq";
//遍历
for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
cout << it->first << '-' << it->second << endl;
cout << endl;
/*输出:
2-zhangsan
6-wangwu
8-lisi
9-pq*/
//输出???
//map自动按键从小到大排序
//unordered_map不会自动排序,但速度较快
unordered_map<int, string> um;
um.insert(pair<int, string>(2, "zhangsan"));
um.insert(make_pair<int, string>(8, "lisi"));
um.insert(unordered_map<int, string>::value_type(6, "wangwu"));
um[9] = "pq";
for (unordered_map<int, string>::iterator it = um.begin(); it != um.end(); it++)
cout << it->first << '-' << it->second << endl;
cout << endl;
/*输出:
2-zhangsan
8-lisi
6-wangwu
9-pq*/
//使用[]插入数据,当出现重复键时,会覆盖之前的键值对
m[9] = "pl";
for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
cout << it->first << '-' << it->second << endl;
cout << endl;
/*输出:
2-zhangsan
6-wangwu
8-lisi
9-pl*/
//map、unordered_map无法直接使用sort(),转成vector
vector<pair<int, string>> v(um.begin(), um.end());
sort(v.begin(), v.end(), cmp);
for (auto x : v)
cout << x.first << '-' << x.second << endl;
cout << endl;
/*输出:
2-zhangsan
6-wangwu
8-lisi
9-pq*/
return 0;
}