C++ map
C++ map
Map is an associative container that contains a sorted list of unique key-value pairs. That list is sorted using the comparison function Compare applied to the keys. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees
Map 是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由 于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义 上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。
下 面举例说明什么是一对一的数据映射。比如一个班级中,每个学生的学号跟他的姓名就存在着一一映射的关系,这个模型用map可能轻易描述,很明显学号用 int描述,姓名用字符串描述(本篇文章中不用char *来描述字符串,而是采用STL中string来描述),下面给出map描述代码:
Map mapStudent;
1. map的构造函数
map共提供了6个构造函数,这块涉及到内存分配器这些东西,略过不表,在下面我们将接触到一些map的构造方法,这里要说下的就是,我们通常用如下方法构造一个map:
Map mapStudent;
2. 数据的插入
在构造map容器后,我们就可以往里面插入数据了。这里讲三种插入数据的方法:
第一种:用insert函数插入pair数据,下面举例说明
- #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 << endl;
- }
第二种:用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 << endl;
- }
第三种:用数组方式插入数据,下面举例说明
- #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";
- /* the below will cover the above
- mapStudent[3] = "student_three_1";
- */
- map<int, string>::iterator iter;
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
- cout << iter->first << " " << iter->second << endl;
- cout << "student size:" << mapStudent.size() << endl;
- }
以
上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的插入上涉
及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值
用pair来获得是否插入成功
- using namespace std;
- int main()
- {
- map<int, string> mapStudent;
- #define MAP_INSERT_CHECK(nr,str) do { \
- pair < map <int, string>::iterator,bool> InsertPair; \
- InsertPair = mapStudent.insert(pair<int, string>(nr, str)); \
- if(InsertPair.second) \
- cout << "Insert Successfully \n"; \
- else \
- cout << "Insert Failure \n" ; \
- }while(0)
- MAP_INSERT_CHECK(1,"student_one");
- MAP_INSERT_CHECK(2,"student_two");
- MAP_INSERT_CHECK(3,"student_three");
- map<int, string>::iterator iter;
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
- cout << iter->first << " " << iter->second << endl;
- cout << "student size:" << mapStudent.size() << endl;
- }
上面已经有iterator方式的遍历了,看看数组方式遍历
- #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 size = mapStudent.size();
- for(int i=0; i<size; i++)
- cout << i+1 << " " << mapStudent[i+1] << endl;
- }
upper_bound,很有意思的东西
- #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;
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
- cout << iter->first << " " << iter->second << endl;
- cout << "student size:" << mapStudent.size() << endl;
- cout << "test bound\n" ;
- iter = mapStudent.lower_bound(2);
- cout <<"lower_bound(2):" <<iter->second << endl;
- iter = mapStudent.upper_bound(2);
- cout <<"upper_bound(2):" <<iter->second << endl;
- iter = mapStudent.lower_bound(3);
- cout <<"lower_bound(3):" <<iter->second << endl;
- iter = mapStudent.upper_bound(3);
- cout <<"upper_bound(3):" <<iter->second << endl;
- /* for justifying exiting */
- pair < map<int,string>::iterator, map<int,string>::iterator > mapPair;
- mapPair = mapStudent.equal_range(2);
- if(mapPair.first == mapPair.second)
- cout <<"key 2 not find\n";
- else
- cout <<"key 2 fount\n";
- mapPair = mapStudent.equal_range(3);
- if(mapPair.first == mapPair.second)
- cout <<"key 3 not find\n";
- else
- cout <<"key 3 fount\n";
- }
反向遍历
看清 不是iterator 而是 reverse_iterator,我是看了好久才检查出来的
- #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 riter;
- for(riter = mapStudent.rbegin(); riter != mapStudent.rend(); riter++)
- cout << riter->first << " " << riter->second << endl;
- }
数据的清空与判空
清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空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>(3, "student_two"));
- mapStudent.insert(pair<int, string>(5, "student_three"));
- map<int, string>::iterator iter;
- cout << "\nthe BILL of all student" << endl;
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter ++)
- cout << iter->first << " " << iter->second << endl;
- cout << "--------------------------" << endl;
- //by iterator
- iter = mapStudent.find(1);
- mapStudent.erase(iter);
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter ++)
- cout << "\t" << iter->first << " " << iter->second << endl;
- //by key
- mapStudent.insert(pair<int, string>(1, "student_one"));
- cout << "\nthe BILL of all student" << endl;
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter ++)
- cout << iter->first << " " << iter->second << endl;
- cout << "--------------------------" << endl;
- int rt = 0;
- rt = mapStudent.erase(1);
- cout << "erase(1):" << rt << endl;
- rt = mapStudent.erase(2);
- cout << "erase(2):" << rt << endl;
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter ++)
- cout << "\t" << iter->first << " " << iter->second << endl;
- //delete a range item
- mapStudent.insert(pair<int, string>(1, "student_one"));
- cout << "\nthe BILL of all student" << endl;
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter ++)
- cout << iter->first << " " << iter->second << endl;
- cout << "--------------------------" << endl;
- mapStudent.erase(mapStudent.begin(), mapStudent.end());
- //Removes the elements in the range [first; last).
- for(iter = mapStudent.begin(); iter != mapStudent.end(); iter ++)
- cout << "\t" << iter->first << " " << iter->second << endl;
- }
排序
因为是红黑树存储,本身要有有顺序,因此在构造时就必须明确iterator->first的比较方法,基本数据类型不说了,如果是结构体有两种,一是在结构体或者类重载“<”,二是利用第三个类进行重载“()”进行排序。
- #include <map>
- #include <iostream>
- #include <string>
- using namespace std;
- typedef struct tagStudentInfo {
- int nID;
- string strName;
- /* in map, the sort need "<" for sorting, so this needed */
- bool operator < (tagStudentInfo const& _A) const {
- if(nID < _A.nID) return true;
- if(nID == _A.nID) return strName.compare(_A.strName) < 0;
- return false;
- }
- }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));
- studentInfo.nID = 3;
- studentInfo.strName = "student_three";
- mapStudent.insert(pair<StudentInfo, int>(studentInfo, 95));
- cout << "ID\tName\t\tScore\n";
- for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++ )
- cout << iter->first.nID <<"\t"
- << iter->first.strName <<"\t"
- << iter->second <<endl ;
- }
第二种
- #include <map>
- #include <iostream>
- #include <string>
- using namespace std;
- typedef struct tagStudentInfo {
- int nID;
- string strName;
- }StudentInfo, *PStudentInfo;
- class BySort{
- 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()
- {
- int nSize;
- map<StudentInfo, int, BySort>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));
- studentInfo.nID = 3;
- studentInfo.strName = "student_three";
- mapStudent.insert(pair<StudentInfo, int>(studentInfo, 95));
- cout << "ID\tName\t\tScore\n";
- for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++ )
- cout << iter->first.nID <<"\t"
- << iter->first.strName <<"\t"
- << iter->second <<endl ;
- }
参考:
http://www.cnblogs.com/wanghao111/archive/2009/08/10/1542974.html
http://en.cppreference.com/w/cpp/container/map
C++ map的更多相关文章
- mapreduce中一个map多个输入路径
package duogemap; import java.io.IOException; import java.util.ArrayList; import java.util.List; imp ...
- .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法
.NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法 0x00 为什么需要Map(MapWhen)扩展 如果业务逻辑比较简单的话,一条主管道就够了,确实用不到 ...
- Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- Java基础Map接口+Collections
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- 多用多学之Java中的Set,List,Map
很长时间以来一直代码中用的比较多的数据列表主要是List,而且都是ArrayList,感觉有这个玩意就够了.ArrayList是用于实现动态数组的包装工具类,这样写代码的时候就可以拉进 ...
- Java版本:识别Json字符串并分隔成Map集合
前言: 最近又看了点Java的知识,于是想着把CYQ.Data V5迁移到Java版本. 过程发现坑很多,理论上看大部分很相似,实践上代码写起来发现大部分都要重新思考方案. 遇到的C#转Java的一些 ...
- MapReduce剖析笔记之八: Map输出数据的处理类MapOutputBuffer分析
在上一节我们分析了Child子进程启动,处理Map.Reduce任务的主要过程,但对于一些细节没有分析,这一节主要对MapOutputBuffer这个关键类进行分析. MapOutputBuffer顾 ...
- MapReduce剖析笔记之七:Child子进程处理Map和Reduce任务的主要流程
在上一节我们分析了TaskTracker如何对JobTracker分配过来的任务进行初始化,并创建各类JVM启动所需的信息,最终创建JVM的整个过程,本节我们继续来看,JVM启动后,执行的是Child ...
- MapReduce剖析笔记之五:Map与Reduce任务分配过程
在上一节分析了TaskTracker和JobTracker之间通过周期的心跳消息获取任务分配结果的过程.中间留了一个问题,就是任务到底是怎么分配的.任务的分配自然是由JobTracker做出来的,具体 ...
- MapReduce剖析笔记之三:Job的Map/Reduce Task初始化
上一节分析了Job由JobClient提交到JobTracker的流程,利用RPC机制,JobTracker接收到Job ID和Job所在HDFS的目录,够早了JobInProgress对象,丢入队列 ...
随机推荐
- Inter IPP的一些基本类型对应的vs中类型
来自为知笔记(Wiz)
- Robot Framework: 自定义自己的python库
利用Robot Framework编写测试用例,往往需要开发自己的关键字,有的关键字需要通过自己编写python代码来实现.这在rf中,就需要自己定义python库.这个过程其实不复杂,本文来介绍下. ...
- ThreadLocal用法和实现原理(转)
如果你定义了一个单实例的java bean,它有若干属性,但是有一个属性不是线程安全的,比如说HashMap.并且碰巧你并不需要在不同的线程中共享这个属性,也就是说这个属性不存在跨线程的意义.那么你不 ...
- haproxy /admin跳转 不会在接口上再次加上admin
http://www.xx.com/admin/api/menu [root@wx03 mojo]# cat test.pl use Mojolicious::Lite; use JSON qw/en ...
- CF 338E Optimize! (线段树)
转载请注明出处,谢谢http://blog.csdn.net/ACM_cxlove?viewmode=contents by---cxlove 出题人题解没看懂...囧. 然后看了下touris ...
- NSThread的一些细节
1.NSThread创建方式(一个NSThread对象就代表一条线程)1.1>创建\启动线程(1)线程一启动,就会在thread中执行self的run方法NSTread *thread = [[ ...
- ssh登录的时候,根本不给输入密码的机会,直接拒绝,是因为BatchMode的设置
BatchMode no“BatchMode”如果设为“yes”,passphrase/password(交互式输入口令)的提示将被禁止.当不能交互式输入口令的时候,这个选项对脚本文件和批处理任务十分 ...
- Oracle 当前时间加减
当我们用 select sysdate+number from dual ;我们得到的是,当前的时间加上number天后的时间.从这里我们也可以看出,使用这种方式进行时间计算的时候,计算的单位是天, ...
- 互联网组织的未来:剖析GitHub员工的任性之源(转)
如果有这么家任性的公司,没有所谓“经理人”这一层,人都在做自己喜欢的事情,并且创造价值,而其他的事情,就顺其自然让他发生.这里能节省多少官僚主义带来的浪费?这样的公司得跑得有多快?得有多少无谓的冲突消 ...
- SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
问题的原因是无法找到org.slf4j.impl.StaticLoggerBinder,我找了一下,确实没有该类,网上搜了一下下面是官方的解答http://www.slf4j.org/codes.ht ...