C++中STL中的map用法详解

合集下载

C++ STL----map

C++ STL----map

C++ STLBy Li-Bangzhu●map解释map(映射)——经过排序了的二元组的集合,map中的每个元素都是由两个值组成,其中的key(键值,一个map中的键值必须是唯一的)是在排序或搜索时使用,它的值可以在容器中重新获取;而另一个值是该元素关联的数值。

比如,除了可以ar[43] ="overripe"这样找到一个数据,map还可以通过ar["banana"] ="overripe"这样的方法找到一个数据。

如果你想获得其中的元素信息,通过输入元素的全名就可以轻松实现。

map一对一的映射的结合,key不能重复。

●map的使用//代码可直接运行,运行环境系统:centos 6.5//此段代码演示了几种不同方法的插入元素,遍历元素,查找,删除元素#include<iostream>#include<map>#include<string>using namespace std;int main(){map<int ,int> mymap; //此map的key和value 都是int 型的map<int ,int>::iterator it; //定义一个迭代子it = mymap.begin();//用数组的方式插入数据for(int i= 0;i<10;i++){mymap[i]= (i+3);}for(it = mymap.begin();it !=mymap.end();it++) //遍历所有元素{cout<<it->first<<" "<<it->second<<endl;}cout<<endl<<endl;//用insert 的方式插入数据for(int j=10;j<20;j++){mymap.insert(pair<int,int>(j,j+10));}for(it= mymap.begin();it != mymap.end();){cout<<it->first<<" "<<it->second<<endl; //遍历所有元素++it;}cout<<endl<<endl;//insert的另外一中方式插入元素for(int k =20; k<30 ;k++){mymap.insert(map<int,int>::value_type(k,k+100));}for(it = mymap.begin();it!=mymap.end();){cout<<it->first<<" "<<it->second<<endl;//遍历所有元素++it;}cout<<"this size of map"<<mymap.size()<<endl;for(int index =0;index<mymap.size();index++){cout<<mymap[index]<<" "; //遍历所有元素}cout<<endl;cout<<mymap[0]<<endl;cout<<mymap[27]<<endl; //随机读取//findit = mymap.find(27);if(it != mymap.end()){cout<<"find,this value"<<endl;//deletemymap.erase(it);}for(int index =0;index<mymap.size();index++){cout<<mymap[index]<<" ";}cout<<endl;//clearmymap.clear();cout<<"the size of mymap"<<mymap.size()<<endl; }更多详情请浏览个人文库:/p/helpylee3Q。

C++学习---STL常用容器之map容器

C++学习---STL常用容器之map容器

C++学习---STL常⽤容器之map容器8、map/multimap 容器8.1、map基本概念简介:map中所有元素都是pairpair中第⼀个元素为key(键值),起到索引作⽤,第⼆个元素为value(实值)所有元素都会根据元素的键值⾃动排序本质:map/multimap属于关联式容器,底层结构是⽤⼆叉树实现。

优点:可以根据key值快速找到value值map和multimap的区别:map不允许容器中有重复key值元素multimap允许容器中有重复key值元素8.2、map构造和赋值#include <iostream>#include <map>using namespace std;/*map<T1,T2> mp; //map默认构造函数map(const map &mp); //拷贝构造函数map& operator=(const map & mp); //重载等号操作符*///map容器构造和赋值void printMap(map<int, int> &m) {for (map<int, int>::iterator it = m.begin(); it != m.end(); it++) {cout << "key = " << (*it).first << " value = " << it->second << endl;}cout << endl;}void test01() {//创建map容器,默认构造map<int, int> m;//匿名对组放⼊容器中,默认按照key排序m.insert(pair<int,int>(1,10));m.insert(pair<int,int>(6,60));m.insert(pair<int,int>(3,30));m.insert(pair<int,int>(4,40));printMap(m);//拷贝构造map<int, int> m2(m);printMap(m2);//赋值map<int, int> m3;m3 = m2;printMap(m3);}int main() {test01();system("pause");return0;}8.3、map⼤⼩和交换#include <iostream>#include <map>using namespace std;/*size(); //返回容器中元素的数⽬empty(); //判断容器是否为空swap(st); //交换两个集合容器*///map容器的⼤⼩和交换void printMap(map<int, int> &m) {for (map<int, int>::iterator it = m.begin(); it != m.end(); it++) {cout << "key:" << it->first << " value:" << it->second << endl; }cout << endl;}void test01() {map<int, int> m;m.insert(pair<int,int>(1,10));m.insert(pair<int,int>(6,60));m.insert(pair<int,int>(3,30));m.insert(pair<int,int>(4,40));if (m.empty()) {cout << "m为空" << endl;}else {cout << "m不为空" << endl;}cout << "m的⼤⼩:" << m.size() << endl;}//交换void test02() {map<int, int> m1;m1.insert(pair<int,int>(1,10));m1.insert(pair<int,int>(2,20));m1.insert(pair<int,int>(3,30));map<int, int> m2;m2.insert(pair<int, int>(5, 500));m2.insert(pair<int, int>(6, 600));cout << "交换前:" << endl;printMap(m1);printMap(m2);m1.swap(m2);cout << "交换后:" << endl;printMap(m1);printMap(m2);}int main() {test01();test02();system("pause");return0;}8.4、map插⼊和删除#include <iostream>#include <map>using namespace std;/*insert(elem); //在容器中插⼊元素clear(); //清除所有元素erase(pos); //删除pos迭代器所指的元素,返回下⼀个元素的迭代器erase(beg,end);//删除区间[beg,end]的所有元素,返回下⼀个元素的迭代器erase(key); //删除容器中值为key的元素*///map容器的插⼊和删除void printMap(map<int, int> &m) {for (map<int, int>::iterator it = m.begin(); it != m.end(); it++) {cout << "key:" << it->first << " value:" << it->second << endl;}cout << endl;}void test01() {map<int, int> m;//第⼀种m.insert(pair<int,int>(1,10));m.insert(pair<int,int>(6,60));//第⼆种m.insert(make_pair(2,20));//第三种m.insert(map<int,int>::value_type(3,30));//第四种,不建议使⽤[]插⼊m[5] = 40;//利⽤key有值的情况进⾏值的访问;//否则在key没有值的情况下,默认给值赋值为0,访问得到0cout << m[2] << endl;printMap(m);//删除m.erase(m.begin());printMap(m);//按照key删除,有则删除m.erase(3);printMap(m);//按照区间的⽅式删除,相当于清空//m.erase(m.begin(),m.end());m.clear();printMap(m);}int main() {test01();system("pause");return0;}8.5、map查找和统计函数原型:find(key); //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回map.end();count(key);//统计key的元素个数#include <iostream>#include <map>using namespace std;/*find(key); //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回map.end();count(key);//统计key的元素个数*///map容器的查找和统计void test01() {map<int, int> m;m.insert(pair<int,int>(1,10));m.insert(pair<int,int>(4,40));//map不允许插⼊重复的keym.insert(pair<int,int>(4,30));m.insert(pair<int,int>(2,20));map<int,int>::iterator pos = m.find(4);if (pos != m.end()) {cout << "查找到了元素 key=" << pos->first << " value=" << pos->second << endl; }else {cout << "未找到元素" << endl;}//统计,cout统计⽽⾔count统计⽽⾔,结果要么是 0,要么是1.//mutimap可以⼤于1int num = m.count(4);cout << "num = " << num << endl;}int main() {test01();system("pause");return0;}8.6、map容器排序利⽤仿函数可以改变排序规则#include <iostream>#include <map>using namespace std;/*map容器默认排序规则为按照key值进⾏从⼩到⼤排序利⽤仿函数可以改变排序规则,即重载了函数调⽤⼩括号*/class MyCompare {public:bool operator()(int v1, int v2){//降序return v1 > v2;}};void printMap(map<int, int, MyCompare> &m) {for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it++) {cout << "key:" << it->first << " value:" << it->second << endl;}cout << endl;}//map容器的排序void test01() {//指定仿函数map<int, int, MyCompare> m;m.insert(pair<int,int>(1,10));m.insert(make_pair(2,20));m.insert(make_pair(5,50));m.insert(make_pair(3,30));printMap(m);}int main() {test01();system("pause");return0;}。

CSTL中Map的按Key排序和按Value排序

CSTL中Map的按Key排序和按Value排序

map是用‎来存放<key, value‎>键值对的数‎据结构,可以很方便‎快速的根据‎k ey查到‎相应的va‎l ue。

假如存储学‎生和其成绩‎(假定不存在‎重名,当然可以对‎重名加以区‎分),我们用ma‎p 来进行存‎储就是个不‎错的选择。

我们这样定‎义,map<strin‎g, int>,其中学生姓‎名用str‎i ng 类型‎,作为Key‎;该学生的成‎绩用int‎类型,作为val‎u e。

这样一来,我们可以根‎据学生姓名‎快速的查找‎到他的成绩‎。

但是,我们除了希‎望能够查询‎某个学生的‎成绩,或许还想看‎看整体的情‎况。

我们想把所‎有同学和他‎相应的成绩‎都输出来,并且按照我‎们想要的顺‎序进行输出‎:比如按照学‎生姓名的顺‎序进行输出‎,或者按照学‎生成绩的高‎低进行输出‎。

换句话说,我们希望能‎够对map‎进行按Ke‎y排序或按‎V alue‎排序,然后按序输‎出其键值对‎的内容。

一、C++ STL中M‎a p的按K‎e y排序其实,为了实现快‎速查找,map内部‎本身就是按‎序存储的(比如红黑树‎)。

在我们插入‎<key, value‎>键值对时,就会按照k‎e y的大小‎顺序进行存‎储。

这也是作为‎k ey的类‎型必须能够‎进行<运算比较的‎原因。

现在我们用‎s trin‎g类型作为‎k ey,因此,我们的存储‎就是按学生‎姓名的字典‎排序储存的‎。

【参考代码】1.#inclu‎d e<map>2.#inclu‎d e<strin‎g>3.#inclu‎d e<iostr‎e am>ing‎names‎p ace std;5.6.typed‎e f pair<strin‎g, int> PAIR;7.8.ostre‎a m& opera‎t or<<(ostre‎a m& out, const‎PAIR& p) {9.retur‎n out << p.first‎<< "\t" << p.secon‎d;10.}11.12.int main() {13. map<strin‎g, int> name_‎s core‎_map;14. name_‎s core‎_map["LiMin‎"] = 90;15. name_‎s core‎_map["ZiLin‎M i"] = 79;16. name_‎s core‎_map["BoB"] = 92;17. name_‎s core‎_map.inser‎t(make_‎p air("Bing",99));18. name_‎s core‎_map.inser‎t(make_‎p air("Alber‎t",86));19.for (map<strin‎g, int>::itera‎t or iter = name_‎s core‎_map.begin‎();20. iter != name_‎s core‎_map.end();21. ++iter) {22. cout << *iter << endl;23. }24.retur‎n 0;25. }【运行结果】大家都知道‎m ap是s‎t l里面的‎一个模板类‎,现在我们来‎看下map‎的定义:1.templ‎a te < class‎Key, class‎T, class‎Compa‎r e = less<Key>,2.class‎Alloc‎a tor = alloc‎a tor<pair<const‎Key,T> > > class‎map;它有四个参‎数,其中我们比‎较熟悉的有‎两个: Key 和 Value‎。

c++中的map的用法

c++中的map的用法

c++中的map的用法Map是一种关联容器,它提供了一种映射的方式,将一个值(value)与一个键(key)相对应。

在C++ STL(Standard Template Library)中,Map是一个非常常用的容器类型,它具有很高的效率和灵活性。

Map内部使用红黑树(一种自平衡的二叉搜索树)来进行高效的查找和插入操作,它的不同之处在于,它的每个节点都包含了一个键值对,其中键是唯一的。

使用Map之前需要引入头文件<map>,其使用方法是:```c++#include <map>map<key_type, value_type> my_map;```key_type表示键的类型,value_type表示值的类型。

Map的常用操作包括:1. 插入Map的插入可以使用insert()函数,例如:```c++//插入键值对//使用数组下标插入my_map["Jerry"] = 20;```2. 查找Map的查找可以使用find()函数,例如:```c++//查找键为"Tom"的值map<string, int>::iterator it = my_map.find("Tom");if (it != my_map.end()) { //如果找到了cout << "Tom's age is " << it->second << endl; //输出Tom的年龄}```3. 删除Map的删除可以使用erase()函数。

例如:```c++//删除键为"Tom"的值my_map.erase("Tom");```4. 遍历Map的遍历可以使用迭代器,例如:```c++//遍历map中的所有键值对for (auto it = my_map.begin(); it != my_map.end(); it++) {cout << "key is " << it->first << " , value is " << it->second << endl;}```需要注意的是,Map中的元素是按照键的大小进行排序的,如果需要按照值的大小进行排序,可以使用multimap容器。

C++ STL模板和Map使用大全

C++ STL模板和Map使用大全

C++ STL模板和Map使用大全C++map的基本操作和使用(2009-09-23 14:58:21)分类:nguages标签:cmap编程基本操作livehaiitMap是c++的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,总结了一些map基本简单实用的操作!1. map最基本的构造函数;map<string , int >mapstring; map<int ,string >mapint;map<sring, char>mapstring; map< char ,string>mapchar;map<char ,int>mapchar; map<int ,char >mapint;2. map添加数据;map<int ,string> maplive;1.maplive.insert(pair<int,string>(102,"aclive"));2.maplive.insert(map<int,string>::value_type(321,"hai"));3, maplive[112]="April";//map中最简单最常用的插入添加!3,map中元素的查找:find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。

map<int ,string >::iterator l_it;;l_it=maplive.find(112);if(l_it==maplive.end())cout<<"we do not find 112"<<endl;else cout<<"wo find 112"<<endl;4,map中元素的删除:如果删除112;map<int ,string >::iterator l_it;;l_it=maplive.find(112);if(l_it==maplive.end())cout<<"we do not find 112"<<endl;else maplive.erase(l_it); //delete 112;5,map中swap的用法:Map中的swap不是一个容器中的元素交换,而是两个容器交换; For example:#include <map>#include <iostream>using namespace std;int main( ){map <int, int> m1, m2, m3;map <int, int>::iterator m1_Iter;m1.insert ( pair <int, int> ( 1, 10 ) );m1.insert ( pair <int, int> ( 2, 20 ) );m1.insert ( pair <int, int> ( 3, 30 ) );m2.insert ( pair <int, int> ( 10, 100 ) );m2.insert ( pair <int, int> ( 20, 200 ) );m3.insert ( pair <int, int> ( 30, 300 ) );cout << "The original map m1 is:";for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )cout << " " << m1_Iter->second;cout << "." << endl;// This is the member function version of swap//m2 is said to be the argument map; m1 the target mapm1.swap( m2 );cout << "After swapping with m2, map m1 is:";for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )cout << " " << m1_Iter -> second;cout << "." << endl;cout << "After swapping with m2, map m2 is:";for ( m1_Iter = m2.begin( ); m1_Iter != m2.end( ); m1_Iter++ )cout << " " << m1_Iter -> second;cout << "." << endl;// This is the specialized template version of swapswap( m1, m3 );cout << "After swapping with m3, map m1 is:";for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )cout << " " << m1_Iter -> second;cout << "." << endl;}6.map的sort问题:Map中的元素是自动按key升序排序,所以不能对map用sort函数:For example:#include <map>#include <iostream>using namespace std;int main( ){map <int, int> m1;map <int, int>::iterator m1_Iter;m1.insert ( pair <int, int> ( 1, 20 ) );m1.insert ( pair <int, int> ( 4, 40 ) );m1.insert ( pair <int, int> ( 3, 60 ) );m1.insert ( pair <int, int> ( 2, 50 ) );m1.insert ( pair <int, int> ( 6, 40 ) );m1.insert ( pair <int, int> ( 7, 30 ) );cout << "The original map m1 is:"<<endl;for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ ) cout << m1_Iter->first<<" "<<m1_Iter->second<<endl;}The original map m1 is:1 202 503 604 406 407 30请按任意键继续. . .7, map的基本操作函数:C++ Maps是一种关联式容器,包含“关键字/值”对begin() 返回指向map头部的迭代器clear()删除所有元素count() 返回指定元素出现的次数empty() 如果map为空则返回trueend() 返回指向map末尾的迭代器equal_range() 返回特殊条目的迭代器对erase() 删除一个元素find() 查找一个元素get_allocator() 返回map的配置器insert() 插入元素key_comp() 返回比较元素key的函数lower_bound() 返回键值>=给定元素的第一个位置max_size() 返回可以容纳的最大元素个数rbegin() 返回一个指向map尾部的逆向迭代器rend() 返回一个指向map头部的逆向迭代器size() 返回map中元素的个数swap() 交换两个mapupper_bound() 返回键值>给定元素的第一个位置value_comp() 返回比较元素value的函数C++map的基本操作和使用(2009-09-23 14:58:21)分类:nguages标签:cmap编程基本操作livehaiitMap是c++的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,总结了一些map基本简单实用的操作!1. map最基本的构造函数;map<string , int >mapstring; map<int ,string >mapint;map<sring, char>mapstring; map< char ,string>mapchar;map<char ,int>mapchar; map<int ,char >mapint;2. map添加数据;map<int ,string> maplive;1.maplive.insert(pair<int,string>(102,"aclive"));2.maplive.insert(map<int,string>::value_type(321,"hai"));3, maplive[112]="April";//map中最简单最常用的插入添加!3,map中元素的查找:find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。

C++中的STL中map用法详解

C++中的STL中map用法详解

C++中的STL中map⽤法详解Map是STL的⼀个关联容器,它提供⼀对⼀(其中第⼀个可以称为关键字,每个关键字只能在map中出现⼀次,第⼆个可能称为该关键字的值)的数据处理能⼒,由于这个特性,它完成有可能在我们处理⼀对⼀数据的时候,在编程上提供快速通道。

这⾥说下map内部数据的组织,map内部⾃建⼀颗红⿊树(⼀种⾮严格意义上的平衡⼆叉树),这颗树具有对数据⾃动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。

1、map简介map是⼀类关联式容器。

它的特点是增加和删除节点对迭代器的影响很⼩,除了那个操作节点,对其他的节点都没有什么影响。

对于迭代器来说,可以修改实值,⽽不能修改key。

2、map的功能⾃动建⽴Key-value的对应。

key 和 value可以是任意你需要的类型。

根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。

快速插⼊Key -Value 记录。

快速删除记录根据Key 修改value记录。

遍历所有记录。

3、使⽤map使⽤map得包含map类所在的头⽂件#include <map> //注意,STL头⽂件没有扩展名.hmap对象是模板类,需要关键字和存储对象两个模板参数:std:map<int,string> personnel;这样就定义了⼀个⽤int作为索引,并拥有相关联的指向string的指针.为了使⽤⽅便,可以对模板类进⾏⼀下类型定义,typedef map<int,CString> UDT_MAP_INT_CSTRING;UDT_MAP_INT_CSTRING enumMap;4、map的构造函数map共提供了6个构造函数,这块涉及到内存分配器这些东西,略过不表,在下⾯我们将接触到⼀些map的构造⽅法,这⾥要说下的就是,我们通常⽤如下⽅法构造⼀个map:map<int, string> mapStudent;5、数据的插⼊在构造map容器后,我们就可以往⾥⾯插⼊数据了。

STL中map的用法剖析

STL中map的用法剖析

STL中map的用法剖析摘要本文深入剖析了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(constvalue_type& X)该方法需要构建一个键值对,即value_type,然后调用insert方法,在该方法中实现根据键值对中的key值查找对应的结点,如果查找到,则不插入当前结点,并返回找到的那个结点,并将pair 中的第二个量置为false;否则插入当前结点,并返回插入的当前结点,且第二个值置为true。

[STL]map按value值查找——find_if的使用

[STL]map按value值查找——find_if的使用

[STL]map按value值查找——find_if的使⽤最近是经常使⽤stl中的map,于是就想记⼀些关于map的东西。

这⼀篇中会讲到map按照value值查找的⽅法,就是find_if函数。

⼤家都知道在map中,排序是按照key值排的,map⾃带的find⽅法也是按着key值查找的,这在某些情况下可能会遇到⼀些⿇烦。

譬如,map<int, char*> m_str中,传⼊⼀个char*需要查找在m_str中是否存在这个字符串,当然你⼤可以使⽤iterator遍历⼀些map,如果你坚持这么做,那就可以直接关闭⽹页了。

1.先来看看find_if的原型:template <class InputIterator, class Predicate>InputIterator find_if(InputIterator first, InputIterator last,Predicate pred){while (first != last && !pred(*first)) ++first;return first;}find_if是⼀个模板函数,接受两个数据类型:InputItearator迭代器,Predicate⽤于⽐较数值的函数或者函数对象(仿函数)。

find_if对迭代器要求很低,只需要它⽀持⾃增操作即可。

当前遍历到的记录符合条件与否,判断标准就是使得pred()为真。

⾄此可能还有些不是很明了,下⾯举⼏个例⼦实际操练下的它的⽤法。

注意观察第三个参数pred。

2.find_if在std::map查找时的应⽤假如我们有个map对象是这么声明的:std::map<int, std::string> mymap;mymap.insert(std::make_pair(20, "USA"));mymap.insert(std::make_pair(10, "CHINA"));mymap.insert(std::make_pair(30, "English"));mymap.insert(std::make_pair(40, "Hongkong"));插⼊值后我们想得到值为”english”的这条记录,要怎样写程序呢?下⾯是个范例参考下:#include <map>#include <string>#include <algorithm>class map_value_finder{public:map_value_finder(const std::string &cmp_string):m_s_cmp_string(cmp_string){}bool operator ()(const std::map<int, std::string>::value_type &pair){return pair.second == m_s_cmp_string;}private:const std::string &m_s_cmp_string;};int main(){std::map<int, std::string> my_map;my_map.insert(std::make_pair(10, "china"));my_map.insert(std::make_pair(20, "usa"));my_map.insert(std::make_pair(30, "english"));my_map.insert(std::make_pair(40, "hongkong"));std::map<int, std::string>::iterator it = my_map.end();it = std::find_if(my_map.begin(), my_map.end(), map_value_finder("English"));if (it == my_map.end())printf("not found\n");elseprintf("found key:%d value:%s\n", it->first, it->second.c_str());return0;}class map_finder即⽤于⽐较的函数对象,它的核⼼就是重载的()运算符。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

STL中map用法详解说明:如果你具备一定的C++ template知识,即使你没有接触过STL,这个文章你也应该可能较轻易的看懂。

本人水平有限,不当之处,望大家辅正。

一.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;(pair<int, string>(1, “student_one”));(pair<int, string>(2, “student_two”));(pair<int, string>(3, “student_three”));map<int, string>::iterator iter;for(iter = (); iter != (); 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;(map<int, string>::value_type (1, “student_one”));(map<int, string>::value_type (2, “student_two”));(map<int, string>::value_type (3, “student_three”));map<int, string>::iterator iter;for(iter = (); iter != (); 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 = (); iter != (); iter++){Cout<<iter->first<<” ”<<iter->second<<end;}}以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值,用程序说明(map<int, string>::value_type (1, “student_one”));(map<int, string>::value_type (1, “student_two”));上面这两条语句执行后,map中1这个关键字对应的值是“student_one”,第二条语句并没有生效,那么这就涉及到我们怎么知道insert语句是否插入成功的问题了,可以用pair来获得是否插入成功,程序如下Pair<map<int, string>::iterator, bool> Insert_Pair;Insert_Pair = (map<int, string>::value_type (1, “student_one”));我们通过pair的第二个变量来知道是否插入成功,它的第一个变量返回的是一个map的迭代器,如果插入成功的话应该是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 =(pair<int, string>(1, “student_one”));If == true){Cout<<”Insert Successfully”<<endl;}Else{Cout<<”Insert Failure”<<endl;}Insert_Pair =(pair<int, string>(1, “student_two”));If == true){Cout<<”Insert Successfully”<<endl;}Else{Cout<<”Insert Failure”<<endl;}map<int, string>::iterator iter;for(iter = (); iter != (); 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 = (); iter != (); iter++)Cout<<iter->first<<” ”<<iter->second<<end;}}3. map的大小在往map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数,用法如下:Int nSize = ();4. 数据的遍历这里也提供三种方法,对map进行遍历第一种:应用前向迭代器,上面举例程序中到处都是了,略过不表第二种:应用反相迭代器,下面举例说明,要体会效果,请自个动手运行程序#include <map>#include <string>#include <iostream>Using namespace std;Int main(){Map<int, string> mapStudent;(pair<int, strin g>(1, “student_one”));(pair<int, string>(2, “student_two”));(pair<int, string>(3, “student_three”));map<int, string>::reverse_iterator iter;for(iter = (); iter != (); iter++){Cout<<iter->first<<” ”<<iter->second<<end;}}第三种:用数组方式,程序说明如下#include <map>#include <string>#include <iostream>Using namespace std;Int main(){Map<int, string> mapStudent;(pair<int, string>(1, “student_one”));(pair<int, string>(2, “student_two”));(pair<in t, string>(3, “student_three”));int nSize = ()for(int nIndex = 0; nIndex < nSize; nIndex++){Cout<<mapStudent[nIndex]<<end;}5. 数据的查找(包括判定这个关键字是否在map中出现)在这里我们将体会,map在数据插入时保证有序的好处。

相关文档
最新文档