首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C++STL中map的使用策略(一)

C++STL中map的使用策略(一)

作者头像
mathor
发布2018-06-22 10:46:41
发布2018-06-22 10:46:41
1.7K0
举报
文章被收录于专栏:mathormathor

Map是STL的一个关联容器,它提供一对一的数据处理能力。比如有一个姓名的集合{“Tom”,”Jone”,”Mary”},班级集合{1,2},班级与姓名可能存在以下的映射关系:

       class(“Tom”) = 2,class(“Jone”) = 2,class(“Mary”) = 1

       我们称其中的姓名集合为关键字集合(key),班级集合为值集合(value)

       在C++中map的实现在一个<map>头文件中

1.构造一个集合

代码语言:javascript
复制
map<T1,T2>m;//名为m的,从T1类型到T2类型的映射

2.插入元素

代码语言:javascript
复制
#include <map>
#include <string>
using namespace std;
int main() {
    map<string, int> dict;
    dict.insert(pair<string, int>("Tom", 1)); // {"Tom"->1}
    dict.insert(pair<string, int>("Jone", 2)); // {"Tom"->1, "Jone"->2}
    dict.insert(pair<string, int>("Mary", 1)); // {"Tom"->1, "Jone"->2, "Mary"->1}
   dict.insert(pair<string, int>("Tom", 2)); // {"Tom"->1, "Jone"->2, "Mary"->1}
    return 0;
}

       在C++中通过insert()方法向集合中插入一个新的映射,参数是一个pair类型的结构。这个pair是另一个STL模板——元祖。pair<int,char>(1,’a’)定义了一个整数1和字符a的pair。我们向映射中加入新映射对的时候就是通过pair来实现的。如果插入的key之前已经有value,不会用插入的新的value替代原来的value,也就是插入无效,但并不会报错。

       是如果插入语句没有生效,那么这就涉及到我们怎么知道insert语句是否插入成功的问题了,可以通过pair来获得是否插入成功,程序如下:

代码语言:javascript
复制
pair<map<int, string>::iterator, bool> insert_pair;
insert_pair = mapStudent.insert(map<int, string>::value_type (1, "student_one"));

       我们通过pair的第二个变量来知道是否插入成功,它的第一个变量返回的是一个map迭代器,如果插入成功的话,insert_pair.second应该是true,否则为false。

       下面给出一个示例代码:

代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;
int main()
{
        map<int, string> mapStudent;
        pair<map<int, string>::iterator, bool> insert_Pair;
    insert_Pair = mapStudent.insert(pair<int, string>(1, "student_one"));
    if(insert_Pair.second == true)
    {
               cout<<"Insert Successfully"<<endl;
    }
    else
    {
        cout<<"Insert Failure"<<endl;
    }
    insert_Pair = mapStudent.insert(pair<int, string>(1, "student_two"));
    if(insert_Pair.second == true)
    {
        cout<<"Insert Successfully"<<endl;
    }
    else
    {
        cout<<"Insert Failure"<<endl;
    }
    map<int, string>::iterator iter;
    for(insert_Pair.first = mapStudent.begin(); insert_Pair.first != mapStudent.end(); insert_Pair.first++)
        {
     cout<<insert_Pair.first -> first<<" "<<insert_Pair.first -> second<<endl;
        }
}

       那么现在问题来了,如果想要覆盖掉原有的值,应该怎么办呢?用数组的访问方式!

代码语言:javascript
复制
//验证数组形式插入数据的效果
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
    map<int,string> mapStudent;
    mapStudent[3] = "student_one";
    mapStudent[1] = "student_two";
    mapStudent[3] = "student_three";
    map<int, string>::iterator iter;
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
        cout<<iter->first<<' '<<iter->second<<endl;
}

3.访问映射

       C++访问映射和数组一样,直接用“[]“就能访问,比如dict[“Tom”]就可以获取“Tom”的班级了。而这里有一个比较特殊的地方,如果没有对“Tom”做过映射的话,此时你访问dict[“Tom”],系统将会自动为“Tom”生成一个映射,其value为对应类型的默认值。当然有些时候我们不希望系统自动为我们生成映射,这时候我们需要检测“Tom”是否已经有映射了。需要用到count()函数进行判断

代码语言:javascript
复制
#include <map>
#include <string>
#include <stdio.h>
using namespace std;
int main() {
    map<string, int> dict;  // {}
    dict["Tom"] = 1; // {"Tom"->1}
    dict["Jone"] = 2; // {"Tom"->1, "Jone"->2}
    //dict["Mary"] = 1; // {"Tom"->1, "Jone"->2, "Mary"->1}
    if (dict.count("Mary")) {
        printf("Mary is in class %d\n", dict["Mary"]);
    } else {
        printf("Mary has no class");
    }
    return 0;
}

       4. 遍历映射

       可以通过迭代器访问映射中的每对映射,每个迭代器的first值对应key,second对应value

代码语言:javascript
复制
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main() {
    map<string, int> dict;  // {}
    dict["Tom"] = 1; // {"Tom"->1}
    dict["Jone"] = 2; // {"Tom"->1, "Jone"->2}
    dict["Mary"] = 1; // {"Tom"->1, "Jone"->2, "Mary"->1}
    for (map<string, int>::iterator it = dict.begin(); it != dict.end(); ++it) {
        cout << it->first << " is in class " << it->second << endl;
    }
    return 0;
}

       5. 删除元素

       移除map中某个值用erase(),它有三个重载函数,下面的示例详细说明了它的用法

代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;
int main()
{
        map<int, string> mapStudent;
    mapStudent.insert(pair<int, string>(1, "student_one"));
    mapStudent.insert(pair<int, string>(2, "student_two"));
    mapStudent.insert(pair<int, string>(3, "student_three"));
    //如果你要演示输出效果,请选择以下的一种,你看到的效果会比较好
    //如果要删除1,用迭代器删除
    map<int, string>::iterator iter;
    iter = mapStudent.find(1);
    mapStudent.erase(iter);
    //如果要删除1,用关键字删除
    int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0
    //用迭代器,成片的删除
    //一下代码把整个map清空
    mapStudent.erase( mapStudent.begin(), mapStudent.end() );
    //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合
    //自个加上遍历代码,打印输出吧
}

       以上只是我列举一些map常用的方法,如果需要更多的功能,可以查看api

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-03-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档