Map是一个关联性容器
map的存储类型是pair<const key,value>的类型
任何两个元素没有相同的key值
map是
1 、构造函数
map<const char*,int>
map<const char*,int,status>
其中status为Comparison类,定义key的排序顺序,也就定义了整个map的key->value对存储顺序
bool status(const char *s1, const char* s2)
{
return strcmp(s1,s2)<0;
}
2、 迭代器
map<const char *key,const char *value>::iterator it;
it -> first; //访问key
it -> second;//访问value
3、常用函数
find(class key)//查找指定的key,返回相应的迭代器位置,找不到则迭代器处于末尾
insert(pair<class key,class value>)//插入一个pair类型的数据
clear()//清空整个map的数据
empty()//判断map是否为空,返回bool类型值
begin()/rbgeion() // 返回迭代器指向第一个/最后一个元素位置
end()/rend( ) //返回最后一个元素下一个位置/第一个元素的下一个位置
4 示例代码
#include "stdafx.h"
#include <iostream>
#include <map>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
map<int,const char *> mymap;
mymap[0] = "Jack";
mymap[1] = "Lucy";
mymap.insert(pair<int,const char *>(3,"Mike"));
mymap.insert(pair<int,const char *>(4,"Lily"));
cout<<"Use iterator"<<endl;
map<int,const char*>::iterator it = mymap.begin();
while (it != mymap.end())
{
cout<<it->first<<"->"<<it->second<<endl;
it++;
}
cout<<"Use reverse_iterator"<<endl;
map<int,const char*>::reverse_iterator reit = mymap.rbegin();
while (reit != mymap.rend())
{
cout<<reit->first<<"->"<<reit->second<<endl;
reit++;
}
it = mymap.find(1);
if ( it != mymap.end())
{
cout<<"use find(1):"<<it->second<<endl;
>}
else
{
cout<<"Cannot find(1)"<<endl;
}
mymap.clear();
mymap[5] = "New";
mymap[6] = "Temp";
cout<<"Current size"<<mymap.size()<<endl;
}
5 所有关于map的函数如下
| Member | Where defined | Description |
|---|---|---|
| key_type | Associative Container | map中的key类型 |
| data_type | Pair Associative Container | key关联的值类型 |
| value_type | Pair Associative Container | 对象类型, pair<const key_type, data_type>,存储在map中 |
| key_compare | Sorted Associative Container | Function object 通过顺序比较 |
| value_compare | Sorted Associative Container< |

本文介绍了C++中Map的基本概念,它是一个关联容器,存储pair<const key, value>类型的数据,确保每个key唯一。文章讲解了Map的构造函数、迭代器的使用,以及find、insert、clear、empty等常用函数的用法,并提供了示例代码,帮助读者快速掌握Map的使用。"
119517914,10499177,数学建模:模型详解与应用,"['数学建模', '算法', '优化算法', '预测分析', '机器学习']
最低0.47元/天 解锁文章
555

被折叠的 条评论
为什么被折叠?



