C++中STL中的map用法详解
- 格式:doc
- 大小:35.50 KB
- 文档页数:7
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容器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;}。
map是用来存放<key, value>键值对的数据结构,可以很方便快速的根据k ey查到相应的val ue。
假如存储学生和其成绩(假定不存在重名,当然可以对重名加以区分),我们用map 来进行存储就是个不错的选择。
我们这样定义,map<string, int>,其中学生姓名用stri ng 类型,作为Key;该学生的成绩用int类型,作为valu e。
这样一来,我们可以根据学生姓名快速的查找到他的成绩。
但是,我们除了希望能够查询某个学生的成绩,或许还想看看整体的情况。
我们想把所有同学和他相应的成绩都输出来,并且按照我们想要的顺序进行输出:比如按照学生姓名的顺序进行输出,或者按照学生成绩的高低进行输出。
换句话说,我们希望能够对map进行按Key排序或按V alue排序,然后按序输出其键值对的内容。
一、C++ STL中Ma p的按Ke y排序其实,为了实现快速查找,map内部本身就是按序存储的(比如红黑树)。
在我们插入<key, value>键值对时,就会按照ke y的大小顺序进行存储。
这也是作为k ey的类型必须能够进行<运算比较的原因。
现在我们用s tring类型作为k ey,因此,我们的存储就是按学生姓名的字典排序储存的。
【参考代码】1.#includ e<map>2.#includ e<string>3.#includ e<iostre am>ingnamesp ace std;5.6.typede f pair<string, int> PAIR;7.8.ostrea m& operat or<<(ostrea m& out, constPAIR& p) {9.return out << p.first<< "\t" << p.second;10.}11.12.int main() {13. map<string, int> name_s core_map;14. name_s core_map["LiMin"] = 90;15. name_s core_map["ZiLinM i"] = 79;16. name_s core_map["BoB"] = 92;17. name_s core_map.insert(make_p air("Bing",99));18. name_s core_map.insert(make_p air("Albert",86));19.for (map<string, int>::iterat or iter = name_s core_map.begin();20. iter != name_s core_map.end();21. ++iter) {22. cout << *iter << endl;23. }24.return 0;25. }【运行结果】大家都知道m ap是st l里面的一个模板类,现在我们来看下map的定义:1.templa te < classKey, classT, classCompar e = less<Key>,2.classAlloca tor = alloca tor<pair<constKey,T> > > classmap;它有四个参数,其中我们比较熟悉的有两个: Key 和 Value。
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++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⽤法详解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的用法剖析摘要本文深入剖析了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,于是就想记⼀些关于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即⽤于⽐较的函数对象,它的核⼼就是重载的()运算符。
stl中map的四种插⼊⽅法总结⽅法⼀:pair例:map<int, string> mp;mp.insert(pair<int,string>(1,"aaaaa"));⽅法⼆:make_pair例:map<int, string> mp;mp.insert(make_pair<int,string>(2,"bbbbb"));⽅法三:value_type例:map<int, string> mp;mp.insert(map<int, string>::value_type(3,"ccccc"));⽅法四:[]例:map<int, string> mp;mp[4] = "ddddd";四种⽅法异同:前三种⽅法当出现重复键时,编译器会报错,⽽第四种⽅法,当键重复时,会覆盖掉之前的键值对。
综合测试:#include<iostream>#include<map>using namespace std;int main(){map<int, string> mp;//map的插⼊⽅法有4种//insert返回值为pair 原型:typedef pair<iterator, bool> _Pairib//⽅法1.pair 在插⼊重复键的情况下前三种⽅法类似,这⾥只测试第⼀种pair<map<int,string>::iterator, bool> pair1 = mp.insert(pair<int,string>(1,"aaaaa11111"));if (pair1.second == true){cout<< "插⼊成功" <<endl;}else{cout<< "插⼊失败" <<endl;}pair<map<int,string>::iterator, bool> pair2 = mp.insert(pair<int,string>(1,"aaaaa22222"));if (pair2.second == true){cout<< "插⼊成功" <<endl;}else{cout<< "插⼊失败" <<endl;}//⽅法2.make_pairmp.insert(make_pair<int,string>(3,"bbbbb33333"));mp.insert(make_pair<int,string>(4,"bbbbb44444"));//⽅法3.value_typemp.insert(map<int, string>::value_type(5,"ccccc55555"));mp.insert(map<int, string>::value_type(6,"ccccc66666"));//⽅法4.[]mp[7] = "ddddd77777";mp[7] = "ddddd88888";for (map<int,string>::iterator it = mp.begin(); it != mp.end(); it++){cout<< it->first << "\t" << it->second <<endl;}cout<< "--------------------------------" <<endl;//删除while(!mp.empty()){map<int,string>::iterator it = mp.begin();cout<< it->first << "\t" << it->second <<endl; mp.erase(it);}return0;}。
stl容器set,map,vector之erase⽤法与返回值详细解析总结本⼈在⼯作中经验教训。
在使⽤ list、set 或 map遍历删除某些元素时可以这样使⽤:复制代码代码如下:std::list< int> List;std::list< int>::iterator itList;for( itList = List.begin(); itList != List.end(); ){if( WillDelete( *itList) ){itList = List.erase( itList);}elseitList++;}复制代码代码如下:std::list< int> List;std::list< int>::iterator itList;for( itList = List.begin(); itList != List.end(); ){if( WillDelete( *itList) ){List.erase(itList++);}elseitList++;}复制代码代码如下:std::list< int> List;std::list< int>::iterator it, next;for( it = List.begin(), next = it, next ++; it != List.end(); it = next, ++next){if( WillDelete( *it) ){List.erase(it);}}注:⽅法三更为巧妙,但需注意⽅法三是⽤前需要判断容器是否为空,否则迭代器会出问题。
我测试得出,set.erase 不返回迭代器,list返回。
vector 删除操作复制代码代码如下:std::vector <PACK_PRINT>::iterator It ;for(It=printItems.begin();It!=printItems.end();){//我是说这⾥怎么判断printItems printItems ⾥PACK_PRINT.bh =0if( It.bh ==0) //是这样吗?{//删除It=printItems.erase(It);}else{//不删除++It;}}复制代码代码如下:std::vector <PACK_PRINT> printItems;int i = 0;while(i < printItems.size()){if(printItems[i].bh == 0) //这⾥⽐如我想把 printItems 时PACK_PRINT.bh =0 的删除如何写哟。
c++映射map的用法在C++的STL标准库中,映射(map)是一种非常重要的容器类型,也是相当复杂的一种容器类型。
映射实现了一个键值对(key-value)的关联式容器,其中每个键(key)唯一地映射到一个值(value)。
在映射中,键是用于索引的,而值则是与键相关联的数据。
这个容器常常用于在C++中实现字典、关联数组以及其他类似的数据结构。
映射类声明如下:```c++template < class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T>> > class map; ```其中,Key是键的数据类型,T是值的数据类型,Compare是键值对的比较函数,默认使用std::less,Allocator是空间配置器,默认使用std::allocator。
在使用其中的映射时,需要注意几个方面。
首先是使用方式,可以通过以下代码定义一个映射:```c++map<string, int> mp;```其中,string是键的数据类型,int是值的数据类型。
定义好映射之后,可以通过以下方式向映射中添加数据:```c++mp["Tom"] = 18;```这行代码所做的操作是,创建一个string类型的键"Tom",然后与值18关联,并将键值对存储到映射容器中。
映射中可以包含多个键值对,因此可以通过以下方式获取映射中的值:```c++cout << mp["Tom"] << endl; //输出18```如果在映射中查找的键不存在, map会自动将其插入一个默认值到映射中。
如果不希望插入默认值,则可以使用find()函数进行查找,例如:```c++map<string, int>::iterator it = mp.find("Tom");if (it != mp.end())cout << it->second << endl;```这样的代码我们不仅可以获取到Tom所对应的数值,还可以判断Tom是否在映射中存在,而不会在不存在的情况下进行自动插入操作。
stl::map遍历并删除元素的⼏种⽅法第⼀种 for循环:#include<map>#include<string>#include<iostream>using namespace std;int main(){map<int,string*> m;m[1]= new string("1111111111111111");m[2]= new string("2222222222222222");m[3]= new string("3333333333333333");m[4]= new string("4444444444444444");m[0]= new string("5555555555555555");map<int,string*>::iterator it;for(it=m.begin();it!=m.end();++it){cout<<"key: "<<it->first <<" value: "<<*it->second<<endl;delete it->second;m.erase(it);}return0;}结果如下:key: 0 value: 5555555555555555key: 1 value: 1111111111111111key: 2 value: 2222222222222222key: 3 value: 3333333333333333key: 4 value: 4444444444444444第⼆种while循环的遍历:#include <map>#include <string>#include <iostream>#include <cstring>using namespace std;struct ltstr{bool operator()(const char* s1, const char* s2) const{return strcmp(s1, s2) < 0;}};int main(){map<const char*, int, ltstr> ages;ages["Homer"] = 38;ages["Marge"] = 37;ages["Lisa"] = 8;ages["Maggie"] = 1;ages["Bart"] = 11;while( !ages.empty() ) {cout << "Erasing: " << (*ages.begin()).first << ", " << (*ages.begin()).second << endl;ages.erase( ages.begin() );}}运⾏结果:Erasing: Bart, 11Erasing: Homer, 38Erasing: Lisa, 8Erasing: Maggie, 1Erasing: Marge, 37更安全的for 循环遍历:#include<map>#include<string>#include<iostream>using namespace std;int main(){map<int,string*> m;m[1]= new string("1111111111111111");m[2]= new string("2222222222222222");m[3]= new string("3333333333333333");m[4]= new string("4444444444444444");m[0]= new string("5555555555555555");map<int,string*>::iterator it;for(it=m.begin();it!=m.end();){cout<<"key: "<<it->first <<" value: "<<*it->second<<endl;delete it->second;m.erase(it++);}return0;}运⾏结果与第⼀种⽅式相同,不过这种删除⽅式也是STL源码⼀书中推荐的⽅式,分析 m.erase(it++)语句,map中在删除iter的时候,先将iter做缓存,然后执⾏iter++使之指向下⼀个结点,再进⼊erase函数体中执⾏删除操作,删除时使⽤的iter就是缓存下来的iter(也就是当前iter(做了加操作之后的iter)所指向结点的上⼀个结点)。
STL 之map 与pair 与unordered_map 常⽤函数详解STL 之map 与pair 与unordered_map 常⽤函数详解⼀、map 的概述map 是STL 的⼀个关联容器,它提供⼀对⼀(其中第⼀个可以称为关键字,每个关键字只能在map 中出现⼀次,第⼆个可能称为该关键字的值)的数据处理能⼒,由于这个特性,它完成有可能在我们处理⼀对⼀数据的时候,在编程上提供快速通道。
这⾥说下map 内部数据的组织,map 内部⾃建⼀颗红⿊树(⼀种⾮严格意义上的平衡⼆叉树),这颗树具有对数据的功能,所以在map 内部所有的数据都是有序的,后边我们会见识到有序的好处。
众所周知,在定义数组的时候⽐如(int array[10]) ,array[0]=25,array[1]=10,其实就是⼀个映射,将0—>25,1—>10,就是将0映射到25,将1映射到10,这种⼀⼀对应的关系就是映射,就数组来说,他的下标和其下标所对应的值就是⼀种映射关系,但是这⼀种关系⽐较死板,于是就有map ,这⼀种容器,。
⼆、map 的定义与初始化(插⼊)单独定义⼀个map :typename1是键值的数据类型typename2是值的数据类型如果是字符串映射到整型数组,键值必须使⽤string 类型,⽽不能使⽤char 数组。
这是因为char 作为数组,不能作为键值。
map 的键和值可以是STL 的容器,我们将set 映射到⼀个字符串三、map 的元素的访问map 中的容器值可以通过:下标和迭代器进⾏访问。
下标访问map 键值是唯⼀的通过迭代器访问map 的迭代器与其他STL 容器相同下⾯来看⼀个⽰例:⾃动排序下⾯举例说明:map 可以建⽴将任何基本类型(包括STL 容器)映射到任何基本数据类型(包括STL 容器)// 引⼊⼀个头⽂件#include <map>map<typename1,typename2> mp;map<set<int>,string> mp;#include <iostream>#include <map>#include <string>using namespace std;int main(){ map<char,int> mp;mp['c']=20;mp['c']=30; // 由于键值唯⼀,第⼀个他的值将会被覆盖cout<<mp['c']<<endl;return 0;}// 输出30map<typename1,typename2>::iterator it;// 由于⼀个it 对应两个值,我们使⽤ it->first 访问键 it->second 访问值PS :下⾯我以3种不同的⽅式进⾏插⼊不懂得可以参照这⼀篇⽂章:// 以类似数组的的表达⽅式来进⾏#include <iostream>#include <map>#include <string>using namespace std;int main(){map<char,int> mp;char key;int val;int t=5;while(t--){cin>>key>>val;mp[key]=val;}// 通过迭代器来访问for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){cout<<it->first<<" "<<it->second<<endl;}return 0;}a 5s 8z 6p 3t 7a 5p 3s 8t 7z 6其实细⼼的⼩伙伴已经发现,其输出结果是按照键值进⾏升序排序的。
stl map的用法STL(Standard Template Library)是C++的标准库之一,包含了许多常用的数据结构和算法。
其中,STL map是一种关联容器,用于存储键值对(key-value pair)。
在使用STL map时,可以采取以下步骤:1. 包含头文件:`#include <map>`。
2. 声明map对象:`std::map<Key, Value> myMap;`,其中Key和Value分别是键和值的类型。
3. 插入键值对:可以使用`myMap.insert(std::make_pair(key, value));`或者`myMap[key] = value;`来插入键值对。
注意,如果插入的键已经存在,则后续的插入操作不会生效。
4. 访问键值对:使用`myMap[key]`可以访问到指定键对应的值。
如果键不存在,则会自动插入一个新的键值对,值初始化为默认值。
5. 查找键值对:可以使用`myMap.find(key)`来查找指定键对应的值。
如果找到了指定键,则返回一个指向该键值对的迭代器,否则返回一个指向末尾的迭代器。
6. 删除键值对:可以使用`myMap.erase(key)`来删除指定键对应的键值对。
7. 遍历键值对:可以使用迭代器来遍历map中的所有键值对。
比如:```cppfor(auto it = myMap.begin(); it != myMap.end(); ++it){std::cout << it->first << " => " << it->second << std::endl;}```除了上述基本用法,STL map还提供了许多其他的成员函数和操作符,可以进行排序、比较、合并等操作。
需要根据具体需求进行选择和使用。
mapstl的用法map是STL的关联式容器,以key-value的形式存储,以红黑树(平衡二叉查找树)作为底层数据结构,对数据有自动排序的功能。
其用法包括:- 命名空间为std,所属头文件为<map>。
- 常用操作:- 容量:- map中实际数据的数据:map.size()。
- map中最大数据的数量:map.max_size()。
- 判断容器是否为空:map.empty()。
- 修改:- 插入数据:map.insert()。
- 清空map元素:map.clear()。
- 删除指定元素:map.erase(it)。
- 迭代器:- map开始指针:map.begin()。
- map尾部指针:map.end()。
- 存储:- map<int, string> map1;- 方法1:map1.insert(pair<int, string>(2, "beijing"));。
- 方法2:map1(4) = "changping";。
- 方法3:map1.insert(map<int, string>::value_type(1, "huilongguan"));。
- 方法4:map1.insert(make_pair<int, string>(3, "xierqi"));。
- 遍历:for (map<int, string>::iterator it=map1.begin(); it!=map1.end(); it++) { cout << it->first << ":" << it->second << endl; }。
- 查找:- 方法1:string value1 = map1(2); if (value1.empty()) { cout << "not found" << endl; }。
C++中的STL中map⽤法详解(零基础⼊门)⽬录⼀、什么是 map ?⼆、map的定义2.1 头⽂件2.2 定义2.3 ⽅法三、实例讲解3.1 增加数据3.2 删除数据3.3 修改数据3.4 查找数据3.5 遍历元素3.6 其它⽅法四、总结map 在编程中是经常使⽤的⼀个容器,本⽂来讲解⼀下 STL 中的 map,赶紧来看下吧!⼀、什么是 map ?map 是具有唯⼀键值对的容器,通常使⽤红⿊树实现。
map 中的键值对是 key value 的形式,⽐如:每个⾝份证号对应⼀个⼈名(反过来不成⽴哦!),其中,⾝份证号就是 key,⼈名便是 value,是单项的关系,可以与 hash 作类⽐。
⼆、map的定义2.1 头⽂件使⽤ map 需要引⼊头⽂件,如下所⽰:#include <map>2.2 定义定义形式如下所⽰:map<key_type, value_type>变量名注意:如果没有 using namespace std, map需要写成 std:map。
来看⼀个简单的例⼦:#include <iostream>#include <map> // 头⽂件#include <string>using namespace std;int main() {map<int, string>node; // 定义变量node[123456] = "张三";cout<<"⾝份证号123456的⼈叫"<<node[123456]<<endl;}输出为:⾝份证号123456的⼈叫张三在上例中,定义了⼀个key 为 int ,value 为 string 的 map 容器 node。
2.3 ⽅法map 最常见的⽅法如下所⽰://常⽤size() // 计算元素个数empty() // 判断是否为空,空返回 trueclear() // 清空容器erase() // 删除元素find() // 查找元素insert() // 插⼊元素count() // 计算指定元素出现的次数begin() // 返回迭代器头部end() // 返回迭代器尾部//⾮常⽤swap() // 交换两个map容器,类型需要相同max_size() // 容纳的最⼤元素个数rbegin() // 指向map尾部的逆向迭代器rend() // 指向map头部的逆向迭代器lower_bound() // 返回键值⼤于等于指定元素的第⼀个位置upper_bound() // 返回键值⼤于指定元素的第⼀个位置equal_range() // 返回等于指定元素的区间三、实例讲解3.1 增加数据⽅法1:以数组下标的形式直接增加,即:变量名[key] = value 的形式。
stl应⽤(map)或字典树(有点东西)Every year, an elephant qualifies to the Arab Collegiate Programming Competition. He graduated this year, but that’s irrelephant. What’s important is that the location of the competition might not have been the same every year. Therefore, after every trip, he always has leftover money in the currency of the country he visited.Now he wants to see how much Jordanian Dinars he has after all those competitions. Can you help him convert the leftover money from all competitions to Jordanian Dinar, if that makes any cents?InputThe first line of input is T – the number of test cases.The first line of each test case contains C and N (1 ≤ C, N ≤ 100000), the number of currency types and the number of competitions, respectively.The next C lines each contain the name of the currency C i of maximum length 10 in lowercase and/or uppercase letters, and the value V i of that currency in Jordanian Dinar (0 < V i ≤ 1000). The names are case-sensitive.The next N lines each contains an amount left over from each competition (0 ≤ N i ≤ 1000), and the name of the currency of that amount (it is guaranteed that the name was either given in the input or is “JD”).OutputFor each test case, print on a single line the total amount of money he has in Jordanian Dinar(JD) rounded to 6 decimal digits.ExampleInput13 5dollar 0.71euro 0.76turkish 0.175.1 dollar6 dollar7 turkish3 euro1.1 JDOutput12.451000https:///sevenjoin/article/details/81943864⾃动建⽴key - value的对应。
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在数据插入时保证有序的好处。