• STL---map


    #include<iostream>
    #include<map>
    #include<algorithm>
    using namespace std;
    
    void func(pair<int, char> t)
    {
        cout << "key: " << t.first << "  value: " << t.second << "
    ";
    }
    
    int main()
    {
        map<int, char> mp;  //无参构造  第一个参数是键值(不能重复),第二个参数可以重复
        mp.insert(pair<int, char>(1, 'a'));
        //pair 是stl为我们写好的一个结构体,照着来就是了,但是这个pair的使用看起来有点繁琐,我们可以使用typedef重命名一下
        typedef pair<int, char>  in_pair;
        mp.insert(in_pair(2, 'b'));
    
        for_each(mp.begin(), mp.end(), func);
    
        //当我们重复插入相同的key的时候,不会报错,但是会返会一个特殊类型
        pair<map<int, char>::iterator, bool> pr;
        pr = mp.insert(in_pair(3, 'c'));
        cout << "是否插入成功 " << pr.second << "
    ";  //输出这个特殊结构的第二个bool类型
        pr = mp.insert(in_pair(3, 'c'));
        cout << "是否插入成功 " << pr.second << "
    ";
    
        return 0;
    }
    View Code
    #include<iostream>
    #include<map>
    #include<algorithm>
    using namespace std;
    
    void func(pair<int, char> t)
    {
        cout << "key: " << t.first << "  value: " << t.second << "
    ";
    }
    
    int main()
    {
        //map的底层实现是红黑树,每一次插入都会引起排序,查找某一个元素的代价是Log(n)
        typedef pair<int, char>  in_pair;
        map<int, char> mp;
        mp.insert(in_pair(1, 'a'));
        mp.insert(in_pair(2, 'b'));
        mp.insert(in_pair(5, 'e'));
        mp.insert(in_pair(4, 'd'));
        mp.insert(in_pair(3, 'c'));
    
        for_each(mp.begin(), mp.end(), func);
    
        map<int, char> mp1;
        mp1.insert(in_pair(6, 'f'));
        mp1.insert(mp.begin(), mp.end());  //使用另一个map来进行插入
    
        cout << "*****************************************
    ";
        for_each(mp1.begin(), mp1.end(), func);
    
        cout << "***************************************
    ";
        map<int, char> mp2(mp);  //构造函数2
        for_each(mp2.begin(), mp2.end(), func);
        cout << "***************************************
    ";
        map<int, char> mp3(mp1.begin(), mp1.end());  //构造函数3
        for_each(mp3.begin(), mp3.end(), func);
    
        return 0;
    }
    View Code
  • 相关阅读:
    20162330 2016-2017-2《程序设计与数据结构》课程总结
    强化学习--Policy Gradient
    59. Spiral Matrix II
    54. Spiral Matrix(剑指offer 19)
    58. Length of Last Word
    c++ string split
    神经网络反向传播,通俗理解
    大话设计模式C++ 备忘录模式
    57. Insert Interval
    c++ sort
  • 原文地址:https://www.cnblogs.com/luojianyi/p/9739849.html
Copyright © 2020-2023  润新知