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对象,丢入队列 ...
随机推荐
- 三种LVS负载均衡技术的优缺点----负载均衡调度算法
三种LVS负载均衡技术的优缺点归纳以下表: VS/NATVS/TUNVS/DR 服务器操作系统任意支持隧道多数(支持Non-arp) 服务器网络私有网络局域网/广域网局域网 服务器数目(100M网络) ...
- gethostbyname()函数说明
gethostbyname()函数说明——用域名或主机名获取IP地址 包含头文件 #include <netdb.h> #include <sys/socket.h> ...
- WCF技术剖析之二十二: 深入剖析WCF底层异常处理框架实现原理[中篇]
原文:WCF技术剖析之二十二: 深入剖析WCF底层异常处理框架实现原理[中篇] 在[上篇]中,我们分别站在消息交换和编程的角度介绍了SOAP Fault和FaultException异常.在服务执行过 ...
- Swift - 使用UI Dynamics给UIKit组件添加移动吸附行为
UI Dynamics是UIKit的一个新组成部分,它向iOS中的视图提供了与物理学有关的功能和动画.可以让你向视图中引入力和物理属性,可以让你的视图弹跳,舞动,受重力影响等等. 下面通过样例,演示使 ...
- 怎样获取浏览器上次的会话数据(session)
怎样获取浏览器上次的会话数据: 要知道上次会话session_id是多少? 让cookie保存的PHPSESSID的值不要浏览器一退出就被删除了? 所以我们要设置自己的session_id,不要系统自 ...
- vi 快捷键积累
依据自己用到的.或者还没记住的.或者用的时候忘了的,慢慢积累. 一.全选复制粘贴. 全选: ggVG // 凝视: gg 光标移到首行 V 进入Visual(可视)模式 G 光标移到最后一行全选 选中 ...
- 使用内容提供者和xml备份联系人
1.通过内容提供者获取联系人信息 package com.ithaimazyh.readcontact; import java.util.ArrayList; import java.util.Li ...
- C#的事件处理机制
链接地址:http://blog.csdn.net/niuox/article/details/7527876 在以往的关于事件处理的程序中,我们更多的是采用一种循环等待的方式,即为了检测某个事件是否 ...
- 通过cmd命令到ftp上下载文件
通过cmd命令到ftp上下载文件 点击"开始"菜单.然后输入"cmd"点"enter"键,出现cmd命令执行框 2 输入"ftp& ...
- [Java聊天室server]实战之二 监听类
前言 学习不论什么一个稍有难度的技术,要对其有充分理性的分析,之后果断做出决定---->也就是人们常说的"多谋善断":本系列尽管涉及的是socket相关的知识,但学习之前,更 ...