码迷,mamicode.com
首页 > 其他好文 > 详细

STL---map

时间:2018-10-04 08:48:40      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:algorithm   span   fun   std   play   \n   begin   splay   first   

技术分享图片
#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

 

STL---map

标签:algorithm   span   fun   std   play   \n   begin   splay   first   

原文地址:https://www.cnblogs.com/luojianyi/p/9739849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!