STL之map
2020-04-28 18:53
1176 查看
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; }
相关文章推荐
- hdu4022_Bombing(STL_map)
- STL中map用法详解
- STL中的map用法详解
- stl遍历map
- 关于STL中的map和hash_map
- 【转】STL中map与hash_map容器的选择
- POJ - 3320 :Jessica's Reading Problem(尺取 - STL(set,map))
- stl 中怎样遍历一个map中的所有元素。请给是实例
- STL中比较常用的容器是vector,set和map,比较常用的算法有Sort等。
- 水果(STL里的map,map尝鲜)
- STL中map的数据结构
- 详细解说STL hash_map
- STL中map容器使用自定义key类型报错详解
- 【C++】STL之容器:vector、set、map
- STL_map——map::begin
- STL中map用法详解
- 动态规划(1) 编程题#2: 滑雪(C++ STL中Map的按Key排序和按Value排序,memset函数直接将数组中的元素全部置成某个数,常函数)
- STL-MAP使用方法总结
- STL-----MAP应用
- STL hash_map 底层初探