map相当于建立了一个键值对的映射,剩下的跟vector有些类似。但是map中的key值是不允许重复的。
今天学习了map的增删改查操作。
#include <iostream>
#include <map>
//map的示例
using namespace std;
int main()
{
//map的功能是自动建立key值到value值的对应
//查找的复杂度是log(N)
//定义map,map中的key值不允许有重复!!!
map<int,char> map_sample;
//使用模板类进行类型定义
typedef map<int,char> MAP_SAMPLE_INT_CHAR;
MAP_SAMPLE_INT_CHAR map_sample2;
//插入元素
map_sample2.insert(map<int,char>::value_type(1,'a'));
map_sample2.insert(map<int,char>::value_type(2,'b'));
cout<<"共有元素个数:"<<map_sample2.size()<<endl;
//根据key查找元素并且判断一个元素是否存在,并删除该元素
map<int,char>::iterator it = map_sample2.find(1);
if(it==map_sample2.end())
{
cout<<"没有找到!"<<endl;
}
else//注意,second 是存储的数据
{
cout<< "找到,存储的数据是" << it->second<<endl;
map_sample2.erase(it);//删除之
}
cout<<"共有元素个数:"<<map_sample2.size()<<endl;
//修改元素
it = map_sample2.find(2);
if(it==map_sample2.end())
{
cout<<"没有找到!"<<endl;
}
else//注意,second 是存储的数据
{
cout<< "找到,存储的数据是" << it->second<<endl;
it->second = 'c';//直接修改
}
it = map_sample2.find(2);
if(it==map_sample2.end())
{
cout<<"没有找到!"<<endl;
}
else//注意,second 是存储的数据
{
cout<< "找到,存储的数据是" << it->second<<endl;
}
return 0;
}