China Open source community
站内导航:
站内排行前50热点文章

精华文章  GDB调试精粹及使用实例
普通文章  STL中map用法详解
精华文章  负载均衡软件比较(Hapr...
普通文章  头文件的重复引用
普通文章  递归函数的调用过程
普通文章  TCP三次握手/四次挥手详解
普通文章  epoll的实现原理
普通文章  贪心策略的理论基础——...
普通文章  BMH算法原理与实现(模...
普通文章  http请求的详细过程
普通文章  DP动态规划
普通文章  GNU LD用法
普通文章  排列组合与回溯算法
普通文章  Linux内核中的红黑树
精华文章  linux下使用minicom的几...
普通文章  Linux socket编程之套接字
精华文章  Android线程模型
精华文章  enum类型的本质
普通文章  Java开源Html解析类库
普通文章  linux源代码包(.tar.g...
普通文章  L.A.M.P配置过程
普通文章  linux设置环境变量的方法
普通文章  python的memcache和jso...
普通文章  应用程序二进制接口---ABI
普通文章  memcached server LRU ...
普通文章  gcc编译过程概述
普通文章  Java多线程实现简单实例
普通文章  android核心模块及相关...
普通文章  linux内核编译问题
普通文章  brk和sbrk详述
普通文章  Python程序员常用的IDE...
普通文章  C/C++程序员常见面试题...
普通文章  优化C语言代码(程序员必...
普通文章  Unix操作系统的历史演变
普通文章  发行版发布:CentOS 5.4
普通文章  模版函数指针,C++委托...
普通文章  在windows中构建gtk开发...
普通文章  在ubuntu9.10下安装QT4...
普通文章  关于Qvariant类--万能的...
普通文章  Debian sudo 设置
普通文章  i++循环与i--循环的执行...
普通文章  busybox1.15.x 交叉编译
普通文章  python非贪婪,多行匹配...
普通文章  cscope使用简介
普通文章  关于僵死进程zombie
普通文章  [翻译]Django初窥
普通文章  函数指针传递和全局指针...
普通文章  Android Porting Exper...
普通文章  判断链表是否存在环并找...
普通文章  递归思想的妙用

 
 
 
当前位置: 首页 >> 程序设计 >> C/C++编程 >> STL中map用法详解
 
 

STL中map用法详解

作者:bpsub      来源:zz     发表时间:2009-10-16     浏览次数:      字号:    

内容摘要 数据,函数,插入,删除,map,排序

由于STL是一个统一的整体,map的很多用法都和STL中其它的东 西结合在一起;map中由于它内部有序,由红黑树保证,因此很多函数执行的时间复杂度都是log2N的,如果用map函数可以实现的功能,而STL Algorithm也可以完成该功能,建议用map自带函数,效率高一些……

Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字 的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一 颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。

下面举例说明什么是一对一的数据映射。比如一个班级中,每个学生的学号跟他的姓名就存在着一一映射的关系,这个模型用map可能轻易描述,很明显学 号用int描述,姓名用字符串描述(本篇文章中不用char *来描述字符串,而是采用STL中string来描述),下面给出map描述代码:

Map<int, string> mapStudent;

1.       map的构造函数

map共提供了6个构造函数,这块涉及到内存分配器这些东西,略过不表,在下面我们将接触到一些map的构造方法,这里要说下的就是,我们通常用如下方法构造一个map:

Map<int, string> mapStudent;

2.       数据的插入

在构造map容器后,我们就可以往里面插入数据了。这里讲三种插入数据的方法:

第一种:用insert函数插入pair数据,下面举例说明(以下代码虽然是随手写的,应该可以在VC和GCC下编译通过,大家可以运行下看什么效果,在VC下请加入这条语句,屏蔽4786警告  #pragma warning (disable:4786) )

#include <map>

#include <string>

#include <iostream>

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”));

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

第二种:用insert函数插入value_type数据,下面举例说明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(map<int, string>::value_type (1, “student_one”));

       mapStudent.insert(map<int, string>::value_type (2, “student_two”));

       mapStudent.insert(map<int, string>::value_type (3, “student_three”));

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

第三种:用数组方式插入数据,下面举例说明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  “student_one”;

       mapStudent[2] =  “student_two”;

       mapStudent[3] =  “student_three”;

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的 插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对 应的值,用程序说明

mapStudent.insert(map<int, string>::value_type (1, “student_one”));

mapStudent.insert(map<int, string>::value_type (1, “student_two”));

上面这两条语句执行后,map中1这个关键字对应的值是“student_one”,第二条语句并没有生效,那么这就涉及到我们怎么知道insert语句是否插入成功的问题了,可以用pair来获得是否插入成功,程序如下

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。

下面给出完成代码,演示插入成功与否问题

#include <map>

#include <string>

#include <iostream>

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(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

大家可以用如下程序,看下用数组插入在数据覆盖上的效果

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  “student_one”;

       mapStudent[1] =  “student_two”;

       mapStudent[2] =  “student_three”;

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

3.       map的大小

在往map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数,用法如下:

Int nSize = mapStudent.size();

4.       数据的遍历

这里也提供三种方法,对map进行遍历

第一种:应用前向迭代器,上面举例程序中到处都是了,略过不表

第二种:应用反相迭代器,下面举例说明,要体会效果,请自个动手运行程序

#include <map>

#include <string>

#include <iostream>

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”));

       map<int, string>::reverse_iterator  iter;

       for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

第三种:用数组方式,程序说明如下

#include <map>

#include <string>

#include <iostream>

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”));

       int nSize = mapStudent.size()

//此处有误,应该是 for(int nIndex = 1; nIndex <= nSize; nIndex++)


//by rainfish

       for(int nIndex = 0; nIndex < nSize; nIndex++)

{

       Cout<<mapStudent[nIndex]<<end;

}

}

5.       数据的查找(包括判定这个关键字是否在map中出现)

在这里我们将体会,map在数据插入时保证有序的好处。

要判定一个数据(关键字)是否在map中出现的方法比较多,这里标题虽然是数据的查找,在这里将穿插着大量的map基本用法。

这里给出三种数据查找方法

第一种:用count函数来判定关键字是否出现,其缺点是无法定位数据出现位置,由于map的特性,一对一的映射关系,就决定了count函数的返回值只有两个,要么是0,要么是1,出现的情况,当然是返回1了

第二种:用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,程序说明

#include <map>

#include <string>

#include <iostream>

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”));

       map<int, string>::iterator iter;

       iter = mapStudent.find(1);

if(iter != mapStudent.end())

{

       Cout<<”Find, the value is ”<<iter->second<<endl;

}

Else

{

       Cout<<”Do not Find”<<endl;

}

}

第三种:这个方法用来判定数据是否出现,是显得笨了点,但是,我打算在这里讲解

Lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器)

Upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器)

例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2,而upper-bound(2)的话,返回的就是3

Equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器,pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字,程序说明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  “student_one”;

       mapStudent[3] =  “student_three”;

       mapStudent[5] =  “student_five”;

       map<int, string>::iterator  iter;

iter = mapStudent.lower_bound(2);

{

       //返回的是下界3的迭代器

       Cout<<iter->second<<endl;

}

iter = mapStudent.lower_bound(3);

{

       //返回的是下界3的迭代器

       Cout<<iter->second<<endl;

}

 

iter = mapStudent.upper_bound(2);

{

       //返回的是上界3的迭代器

       Cout<<iter->second<<endl;

}

iter = mapStudent.upper_bound(3);

{

       //返回的是上界5的迭代器

       Cout<<iter->second<<endl;

}

 

Pair<map<int, string>::iterator, map<int, string>::iterator> mapPair;

mapPair = mapStudent.equal_range(2);

if(mapPair.first == mapPair.second)
       {

       cout<<”Do not Find”<<endl;

}

Else

{

Cout<<”Find”<<endl;
}

mapPair = mapStudent.equal_range(3);

if(mapPair.first == mapPair.second)
       {

       cout<<”Do not Find”<<endl;

}

Else

{

Cout<<”Find”<<endl;
}

}

6.       数据的清空与判空

清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map

7.       数据的删除

这里要用到erase函数,它有三个重载了的函数,下面在例子中详细说明它们的用法

#include <map>

#include <string>

#include <iostream>

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.earse(mapStudent.begin(), mapStudent.end());

       //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合

 

       //自个加上遍历代码,打印输出吧

}

8.       其他一些函数用法

这里有swap,key_comp,value_comp,get_allocator等函数,感觉到这些函数在编程用的不是很多,略过不表,有兴趣的话可以自个研究

9.       排序

这里要讲的是一点比较高深的用法了,排序问题,STL中默认是采用小于号来排序的,以上代码在排序上是不存在任何问题的,因为上面的关键字是int 型,它本身支持小于号运算,在一些特殊情况,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号操作,insert等函数在编译的时候过 不去,下面给出两个方法解决这个问题

第一种:小于号重载,程序举例

#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

}StudentInfo, *PStudentInfo;  //学生信息

 

Int main()

{

    int nSize;

       //用学生信息映射分数

       map<StudentInfo, int>mapStudent;

    map<StudentInfo, int>::iterator iter;

       StudentInfo studentInfo;

       studentInfo.nID = 1;

       studentInfo.strName = “student_one”;

       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

       studentInfo.nID = 2;

       studentInfo.strName = “student_two”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

 

for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)

    cout<<iter->first.nID<<endl<<iter->first.strName<<endl<<iter->second<<endl;

 

}

以上程序是无法编译通过的,只要重载小于号,就OK了,如下:

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

       Bool operator < (tagStudentInfo const& _A) const

       {

              //这个函数指定排序策略,按nID排序,如果nID相等的话,按strName排序

              If(nID < _A.nID)  return true;

              If(nID == _A.nID) return strName.compare(_A.strName) < 0;

              Return false;

       }

}StudentInfo, *PStudentInfo;  //学生信息

第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载,程序说明

#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

}StudentInfo, *PStudentInfo;  //学生信息

 

Classs sort

{

       Public:

       Bool operator() (StudentInfo const &_A, StudentInfo const &_B) const

       {

              If(_A.nID < _B.nID) return true;

              If(_A.nID == _B.nID) return _A.strName.compare(_B.strName) < 0;

              Return false;

       }

};

 

Int main()

{

       //用学生信息映射分数

       Map<StudentInfo, int, sort>mapStudent;

       StudentInfo studentInfo;

       studentInfo.nID = 1;

       studentInfo.strName = “student_one”;

       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

       studentInfo.nID = 2;

       studentInfo.strName = “student_two”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

}

10.   另外

由于STL是一个统一的整体,map的很多用法都和STL中其它的东西结合在一起,比如在排序上,这里默认用的是小于号,即less<>,如果要从大到小排序呢,这里涉及到的东西很多,在此无法一一加以说明。

还要说明的是,map中由于它内部有序,由红黑树保证,因此很多函数执行的时间复杂度都是log2N的,如果用map函数可以实现的功能,而STL  Algorithm也可以完成该功能,建议用map自带函数,效率高一些。

下面说下,map在空间上的特性,否则,估计你用起来会有时候表现的比较郁闷,由于map的每个数据对应红黑树上的一个节点,这个节点在不保存你的 数据时,是占用16个字节的,一个父节点指针,左右孩子指针,还有一个枚举值(标示红黑的,相当于平衡二叉树中的平衡因子),我想大家应该知道,这些地方 很费内存了吧,不说了……


--------------------------------------------------

om摘  要 本文深入剖析了C++标准模板库(STL)中的map,对其概念和用法进行了深入探讨,并结合实例,详细阐述了map的相关用法。

    关键词 STL;map;插入;删除;排序  
1 map概述     STL(Standard Template Library 标准模版库)是C++标准程序库的核心,它深刻 影响 了标准程序库的整体结构。STL是一个范型(generic)程序库,提供一系列软件方案,利用先进、高效的算法来管理数据。STL的好处在于封装了许多 数据结构和算法(algorithm),map就是其典型代表。 map是STL的一个关联容器,它提供一对一(key/value 其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可以称为该关键字的值)的数据处理能力,由于这个特性,在处理一对一数据的时候,可以提供编程的快速通道。 2 map的用法     假设一个班级中,每个学生的学号和他的姓名存在一一映射的关系,这个模型用map可以轻易描述,学号用int描述,姓名用字符串描述,给出map的描述代码:map<int, string> mapStudent 。 2.1  插入数据     map元素的插入功能可以通过以下操作实现:     第一种通过主键获取map中的元素,如果获取到,则返回对应结点对应的实值(存储在map结点中的 对象)。但这个 方法 会产生副作用,如果以主键“key”获取结点的实值,在map中并不存在这个结点,则会直接向map中插入以key为主键的结点,并返回这个结点,这时可 以对其进行赋值操作。但如果在map中存在了以key为主键的结点,则会返回这个结点的实值,如果此时进行复制操作,则会出现原来结点被新结点覆盖的危 险,如果是指针类型则会出现内存泄漏等 问题 。由于存在这样的副作用,不建议使用这种方法进行元素的插入。     第二种插入value_type数据。     insert方法接口原型:pair<ierator, bool> insert(const value_type& X) 该方法需要构建一个键值对,即value_type,然后调用insert方法,在该方法中实现根据键值对中的key值查找对应的结点,如果查 找到,则不插入当前结点,并返回找到的那个结点,并将pair中的第二个量置为false;否则插入当前结点,并返回插入的当前结点,且第二个值置为 true。在插入结点的时候,在map内部会重新构造一个新的value_type结点并将传入的X进行copy构造,内部使用了placement new方式,通过内存分配器分配一个map结点,再在获取的结点空间中调用value_type构造函数。所以调用者构造的键值对value_type是 一个临时变量,不会加入到map中(不要被引用操作符迷惑,这里仅仅是传参效率上的考虑)。这种结点插入的方式是安全的,建议使用这种方式向map中插入 元素,并判断返回的插入结果,根据插入结果进行后续处理。 #pragma warning(disable:4786) #include <map> #include <string> #include <iostream> using namespace std; int main() { map<int,string> mapStudent; mapStudent.insert(map<int,string>::value_type(1,"one")); mapStudent.insert(map<int,string>::value_type(2,"two")); mapStudent.insert(map<int,string>::value_type(3,"three")); map<int,string>::iterator iter; for(iter=mapStudent.begin();iter!=mapStudent.end();iter++) {      cout<<iter->first<<" "<<iter->second<<endl; } } 2.2  map的大小     往map中插入了数据,可以用size()函数得到当前已经插入了多少数据: int nSize=mapStudent.size() 2.3  排序     STL中默认是采用小于号来排序的,以上代码在排序上是不存在任何问题的,因为上面例子中的关键字 是int型,它本身支持小于号运算。在一些特殊情况下,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号运算,insert等函数在编 译的时候过不去。给出一种方法解决排序问题小于号重载。 #pragma warning(disable:4786) #include <map> #include <string> #include <iostream> using namespace std; typedef struct tagStudentInfo { int nID; string strName; } StudentInfo, *PStudentInfo;   // 学生信息 int main() { //用学生信息映射分数 map<StudentInfo, int> mapStudent; StudentInfo studentInfo; studentInfo.nID=2; studentInfo.strName="one"; mapStudent.insert(map<StudentInfo, int>::value_type (studentInfo,90)); studentInfo.nID=1; studentInfo.strName="two"; mapStudent.insert(map<StudentInfo, int>::value_type (studentInfo,80)); } 以上程序无法编译通过,需要重载小于号。 typedef struct tagStudentInfo { int nID; string strName; bool operator <(tagStudentInfo const& _A) const {//这个函数指定排序策略,按nID排序,如果nID相等按strName排序 if(nID<_A.nID)  return true; if(nID==_A.nID) return strName.compare(_A.strName) <0; return false; } } StudentInfo, *PStudentInfo; 
2.4  map中结点的删除操作     两种 应用 场景:     第一种:一次只从map中查找一个结点并删除。     这种删除较为简单,只需要根据键值在map中查找,并将找到的结点删除就可以了。中国论文联盟http://www.lwlm.com #pragma warning(disable:4786) #include <map> #include <string> #include <iostream> using namespace std; void main() { map<int,string> mapStudent; mapStudent.insert(map<int,string>::value_type(1,"one")); mapStudent.insert(map<int,string>::value_type(2,"two")); mapStudent.insert(map<int,string>::value_type(3,"three")); map<int,string>::iterator iter; iter=mapStudent.find(1); mapStudent.erase(iter); for(iter=mapStudent.begin();iter!=mapStudent.end();iter++) {      cout<<iter->first<<" "<<iter->second<<endl; } }     第二种:从map中遍历检查所有结点,将符合条件的结点删除。     应用场景描述:系统定期检查垃圾会话(会话放在map表中),根据当前系统时间减去会话最近活动时间,得到会话最近未活动时间间隔,如果这个间隔超过预定的值(认为会话是垃圾会话,可以被强制删除),则删除该会话并从map中删除这个结点。     做法有两种:     (1)先遍历一遍map,找出所有满足条件的结点,将每一个对应结点的key放入一个vector中,后面再从vector中依次取出key值,做单结点删除操作。     这种 方法 是很原始且效率低下的做法,之所以会这样实现,是由于开发人员对map使用不甚了解的基础上做出来的。这种方法不但增加了中间处理过程的系统开销(多构建 了一个缓存空间),而且多了N(待删除结点的结点数)次的查询操作,对于经常出现的操作,这种低效是不可容忍的。     (2)在map遍历的过程中,完成对符合条件结点的删除操作(这个是由map本身数据结构特性保证 的)。在遍历的过程中最主要的就是怎么保证删除的结点在删除前将指针指向下一个结点(这一点正是我们要做的),在删除了当前结点后,map中的数据结构能 够保证后续的迭代器指针是有效的,而且后续的结点都没有遍历过(这个特性是由map底层的红黑树的相关操作保证的)。所以需要将迭代器指向下一个结点后再 删除当前符合条件的结点。 #pragma warning(disable:4786) #include <map> #include <string> #include <iostream> using namespace std; void main() { map<int,string> mapStudent; mapStudent.insert(map<int,string>::value_type(1,"one")); mapStudent.insert(map<int,string>::value_type(2,"two")); mapStudent.insert(map<int,string>::value_type(3,"three")); map<int,string>::iterator iter; string aa="three"; iter=mapStudent.begin(); for(;iter!=mapStudent.end();) {      if((iter->second)>=aa)      {          //满足删除条件,删除当前结点,并指向下面一个结点               mapStudent.erase(iter++);      }      else      {      //条件不满足,指向下面一个结点      iter++;      } } for(iter=mapStudent.begin();iter!=mapStudent.end();iter++) {      cout<<iter->first<<" "<<iter->second<<endl; } }     这种删除方式也是STL源码一书中推荐的方式。比较一下mapStudent.erase(iter++)和mapStudent.erase(iter); iter++;这个执行序列。不妨做个简单的测试,看看汇编执行下的执行序列: void func(int a) {} int main(int, char**) { int iPos=0; func(iPos++); }     函数调用func(iPos++)执行序列:将iPos放入寄存器edx中(缓存起来),随机对 iPos做加操作 inc dword ptr [ebp-0x04]。也就是说函数调用中的iPos++的执行时期在函数体func执行前就已经完成,而函数体中的参数使用的是iPos未做加操作之前 的副本。再 分析 mapStudent.erase(iter++)语句,map中在删除iter的时候,先将iter做缓存,然后执行iter++使之指向下一个结点, 再进入erase函数体中执行删除操作,删除时使用的iter就是缓存下来的iter(也就是当前iter(做了加操作之后的iter)所指向结点的上一 个结点)。     根据以上分析,可以看出mapStudent.erase(iter++)和map Student.erase(iter); iter++;这个执行序列是不相同的。前者在erase执行前进行了加操作,在iter被删除(失效)前进行了加操作,是安全的;后者是在erase执 行后才进行加操作,而此时iter已经被删除(当前的迭代器已经失效了),对一个已经失效的迭代器进行加操作,行为是不可预期的,这种写法势必会导致 map操作的失败并引起进程的异常。 3 结束语     充分利用map的强大功能,可以使程序员的工作量大大减轻,采用传统方法编写的许多行代码,往往通过调用一两个算法模板就可实现。map技术可以让程序员编写出简洁而高效的代码,使编程工作更加简单而有效。 参考 文献 [1] Nicolai M.Josuttis. C++标准程序库[M]. 武汉: 华中 科技 大学出版社,2006. [2] Scott Meyers. Effective STL中文版50条有效使用STL的经验[M]. 北京: 清华大学出版社,2006. [3] 侯捷. STL源码剖析[M]. 武汉: 华中科技大学出版社,2002. [4] 王昌晶,薛锦云. 从C++到STL[J]. 江西师范大学学报,2004(8):231-234.

编辑 bpsub

 
 
 
 
中国源码网 - www.YuanMa.org - 中国 开放源代码+编程 社区