zoukankan      html  css  js  c++  java
  • 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; }
  • 相关阅读:
    mac os programming
    Rejecting Good Engineers?
    Do Undergrads in MIT Struggle to Obtain Good Grades?
    Go to industry?
    LaTex Tricks
    Convert jupyter notebooks to python files
    How to get gradients with respect to the inputs in pytorch
    Uninstall cuda 9.1 and install cuda 8.0
    How to edit codes on the server which runs jupyter notebook using your pc's bwroser
    Leetcode No.94 Binary Tree Inorder Traversal二叉树中序遍历(c++实现)
  • 原文地址:https://www.cnblogs.com/love-ziji/p/12783089.html
Copyright © 2011-2022 走看看