• STL之map


    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; }
  • 相关阅读:
    js禁止鼠标右键功能
    js判断客户端是pc还是手机及获取浏览器版本
    js实现深拷贝的一些方法
    python使用requests请求的数据乱码
    PyCharm引入python需要使用的包
    几个常见用于解决nginx负载均衡的session共享问题的办法
    面试最让你手足无措的一个问题:你的系统如何支撑高并发?
    Linux/Windows 平台最容易安装 Composer教程
    Laravel一些常用命令整理
    nginx下重写隐藏index.php文件
  • 原文地址:https://www.cnblogs.com/love-ziji/p/12783089.html
Copyright © 2020-2023  润新知