STL---map

#include<iostream>
#include<map>
#include<algorithm>
using namespace std;

void func(pair<int, char> t)
{
    cout << "key: " << t.first << "  value: " << t.second << "\n";
}

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 << "\n";  //输出这个特殊结构的第二个bool类型
    pr = mp.insert(in_pair(3, 'c'));
    cout << "是否插入成功 " << pr.second << "\n";

    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 << "\n";
}

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 << "*****************************************\n";
    for_each(mp1.begin(), mp1.end(), func);

    cout << "***************************************\n";
    map<int, char> mp2(mp);  //构造函数2
    for_each(mp2.begin(), mp2.end(), func);
    cout << "***************************************\n";
    map<int, char> mp3(mp1.begin(), mp1.end());  //构造函数3
    for_each(mp3.begin(), mp3.end(), func);

    return 0;
}
View Code

 

posted @ 2018-10-03 15:17  清浅...忆回  阅读(69)  评论(0编辑  收藏  举报