当前位置: 移动技术网 > IT编程>开发语言>C/C++ > STL之map

STL之map

2020年04月28日  | 移动技术网IT编程  | 我要评论

重庆丝袜论坛,极品强盗,清明上河图成品价

map是stl的一个关联容器,它提供一对一的数据处理能力,其中第一个称为关键字,每个关键字只能在map中出现一次,第二个称为该关键字的值(常称为键值对)。

#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; }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网