map简要用法

map.find()
用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,程序说明
#include
#include
#include
Using namespace std;Int main()
{ Map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, “student_one”));
mapStudent.insert(pair<int, string>(2, “student_two”)); mapStudent.insert(pair<int, string>(3, “student_three”));
map<int, string>::iterator iter;
iter = mapStudent.find(1);
if(iter != mapStudent.end())
{ Cout<<”Find, the value is ”<second<<endl;}
Else{ Cout<<”Do not Find”<<endl;}
}
c++ map 插入数据后,begin(),end()以及当前迭代器的变化

1. map.end()指向map的最后一个元素之后的地址,无论执行map.erase(iter)还是map.add(key, value),map.end()所返回的值永远不会发生变化,都是指向同一块内存。
  1. map.begin()指向map的第一个元素,map.begin()可能随着map.erase(iter)或是map.add(key, value)操作而发生改变。例如当第一个元素被删除后,map.begin()就发生了改变,指向原来第一个元素之后的那个元素了。或是如果新插入一个键值对,该键值对的key放到btree(我们假设map内部是由btree实现的,实际上也可能有别的实现方式)中会排在map.begin()->first的前面,那么map.begin()也会指向新插入的这个键值对了。
  2. map.erase(iter)执行后,当前iter就失去意义了,再执行++iter就会出问题。
  3. 4,插入数据

(1)my_Map[“a”]=1;

改变map中的条目非常简单,因为map类已经对[]操作符进行了重载

enumMap[1] = “One”;

enumMap[2] = “Two”;
例子:
void select_element(string a1, map<char,int> & maps,int &n,string &h)
{
map<char,int>::iterator it,is;
for(int i=0;i<a1.length();i++)
{
it = maps.find(a1[i]);
if(it != maps.end())
(it->second)++;
else
{ maps[ a1[i] ] = 1; n++;}
}
is=maps.end();
is–;
for(it=maps.begin();it!=maps.end();it++)
{
h+=it->first;
cout<first<<":"<second;
if(it!=is) cout<<" "; //最后一个无空格!!例 a:2()b:3()c:4() 错误
} //a:2()b:3()c:4 正确
cout<<endl;
}
效果:aaaaaaabbbbbccdddd ------>a:7 b:5 c:2 d:4

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值