c++中map的相关函数及用法(整理)

map是STL提供的关联容器,提供一对一的hash,以(key,value)的形式存在,可以储存任意类型的数据。map中的元素自动按key的升序排序。
头文件:#include<map>
定义:
map<char,int> temp1;
map<int,string> temp2;
访问:
通过下标访问:temp1[‘c’],temp2[i];
通过迭代器进行访问:it->first访问key,it->second访问value;
例:map<char,int>::iterator it;
it=temp1.begin();
添加数据:
insert函数插入pair数据:temp2.insert(pair<int,string>(1,”sss”));
insert函数插入value_type数据:temp2.insert(map<int,string>::value_type(2,”ssss”));
数组方式插入:temp[2]=”ssssss”;{可以覆盖之前的赋值}
查找元素:
find(key):返回一个迭代器指向键值为key的元素,没找到返回指向map尾部的迭代器;
删除元素:
 迭代器删除:it=temp2.find(“1”); temp2.erase(it);
 关键字删除:int res=temp2.erase(“1”);{删除会返回1,否则返回0};
 迭代器范围删除:temp2.erase(temp2.begin()+m,temp2.end()-n);{0<=m,n<map长度};
 删除所有元素:temp2.clear();
map的基本操作函数:
1.返回指定元素的个数:temp1.count("a");
2.返回map中元素的个数:temp1.size();
3.交换两个map:swap(temp1,temp);
4.返回可以容纳的最大元素个数:temp2.max_size();
5.判断map是否为空:temp1.empty();
6.逆向迭代器:map<int,string>::reverse_iterator it;指向尾部temp1.rbegin();指向头部temp1.rend();
7.返回特殊条目的迭代器对:返回一对迭代器i和j,i为不破坏次序的前提下,value可以插入的第一个位置lower_bound;j为在不破坏次序的前提下,value可插入的最后一个位置upper_bound;[i,j)的每个元素都等同于value,且[i,j)是[first,last)内符合这一性质的最大子区间。
例:pair<map<char,int>::iterator,map<char,int>::iterator> ret=temp1.equal_range(‘b’);
8.返回与map关联的配置器:
map<char,int>::allocator_type m=temp1.get_allocator();{m=allocator<pair<char,int>>};
9.返回比较元素key的容器使用的比较对象:
map<char,int>::key_compare mycomp=temp1.key_comp();
char high=temp1.rbegin()->first;
it=temp1.begin();

do{
cout<<it->first<<”=>”<<it->second<<endl;
}while(mycomp((*it++).first,high)){key值为high时,循环终止}
10.返回比较元素value的函数:
it=temp1.begin();
pair<int,char> last=*temp1.rbegin();
do{
cout<<it->first<<”=>”<<it->second<<endl;
}while(temp1.value_comp()(*it++,last));{value值为last时,循环终止}

  • 1
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值