C++ STL☞map

        map是映射,是一种比较常用的容器。采用键值对的方式,与python中的“字典”或者PHP中的关联数组比较相似。今天我就学习一下map容器。


map就是从key到value的映射。

        在STL模板中,有许多对map进行操作的函数。比如insert()、count()、find()等等等等。如果想要对map容器进行遍历,则需要借助迭代器iterator。

        在插入时,我现在只学习了两种方式,一种是利用pair,另一种是借助数组的形式,因为重载了“[]”运算符,因此,map的写法像是数组的“高级版”。一会会利用这两种方式举个小栗子帮助理解。

        此时,pair是什么可能会引起大家的注意。pair的功能是将一对值组合成一个值。例如:

pair<int,string>(1,"one");

此时,我们就将 (1,“one”)这样一对值组合成了一个值。


下面,我利用代码对map容器写一个小栗子,第一个例子是通过pair插入到map容器中。

#include<map>       //map头文件
#include<string>
#include<iostream>

using namespace std;

int main()
{
    map<int,string>mapStu;//定义一个名为mapStu的map容器

    /*
        第一种插入方法:因为是一对值,因此可以利用pair插入
    */
    mapStu.insert(pair<int,string>(1,"Stuone"));
    mapStu.insert(pair<int,string>(2,"Stutwo"));
    mapStu.insert(pair<int,string>(3,"Stuthree"));

    //对map容器利用迭代器遍历

    map<int,string>::iterator iter;
    for(iter = mapStu.begin(); iter != mapStu.end(); iter++)
    {
        //输出键是用 iter->first
        //输出value是用 iter->second
        cout<<iter->first<<" "<<iter->second<<endl;
    }

    /*
        在容器中查找是否有键为3的,此时需要利用迭代器进行查找
    */
    map<int,string>::iterator fff;
    fff  = mapStu.find(3);
    if(fff != mapStu.end())
    {
        cout<<"在容器中存在键为3,其值为:"<<fff->second<<endl;
    }
    else cout<<"在容器中不存在键为3的"<<endl;
}




第二个例子是 使用[]对map容器进行插入数据,其余不变。

#include<map>       //map头文件
#include<string>
#include<iostream>

using namespace std;

int main()
{
    map<int,string>mapStu;//定义一个名为mapStu的map容器

    /*
        第一种插入方法:因为是一对值,因此可以利用pair插入
    */
    mapStu[0] = "Stu0";
    mapStu[1] = "Stu1";
    mapStu[2] = "Stu2";

    //对map容器利用迭代器遍历

    map<int,string>::iterator iter;
    for(iter = mapStu.begin(); iter != mapStu.end(); iter++)
    {
        //输出键是用 iter->first
        //输出value是用 iter->second
        cout<<iter->first<<" "<<iter->second<<endl;
    }

    /*
        在容器中查找是否有键为3的,此时需要利用迭代器进行查找
    */
    map<int,string>::iterator fff;
    fff  = mapStu.find(3);
    if(fff != mapStu.end())
    {
        cout<<"在容器中存在键为3,其值为:"<<fff->second<<endl;
    }
    else cout<<"在容器中不存在键为3的"<<endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值