4.数据的遍历
这里也提供三种方法,对map进行遍历
第一种:应用前向迭代器,上面举例程序中到处都是了,略过不表
第二种:应用反相迭代器,下面举例说明,要体会效果,请自个动手运行程序
#include<map>
#include<string>
#include<iostream>
using
int
{
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>::reverse_iterator
for(iter=mapStudent.rbegin();iter!=mapStudent.rend();iter++)
{
cout<<iter->first<<"
}
}
第三种:用数组方式,程序说明如下
#include<map>
#include<string>
#include<iostream>
using
int
{
map<int,string>mapStudent;
mapStudent.insert(pair<int,string>(1,"student_one"));
mapStudent.insert(pair<int,string>(2,"student_three"));
mapStudent.insert(pair<int,string>(3,"student_three"));
int
for(int
{
cout<<mapStudent[nindex]<<endl;
}
}
5.数据的查找(包括判定这个关键字是否在map中出现)
要判定一个数据(关键字)是否在map中出现的方法比较多,这里标题虽然是数据的查找,在这里将穿插着大量的map基本用法。
这里给出三种数据查找方法
第一种:用count函数来判定关键字是否出现,其缺点是无法定位数据出现位置,由于map的特性,一对一的映射关系,就决定了count函数的返回值只有两个,要么是,要么是,出现的情况,当然是返回了
第二种:用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,程序说明
#include<map>
#include<string>
#include<iostream>
using
int
{
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=mapStudent.find(1);
if(iter!=mapStudent.end())
{
cout<<"Find,the
}
else
cout<<"Do
}
第三种:这个方法用来判定数据是否出现,是显得笨了点,但是,我打算在这里讲解
Lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器)
Upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器)
例如:map中已经插入了,,,的话,如果lower_bound(2)的话,返回的,而upper-bound()的话,返回的就是
Equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器,pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字,程序说明
#include<map>
#include<string>
#include<iostream>
using
int
{
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"));
mapStudent.insert(pair<int,string>(5,"student_five"));
map<int,string>::iterator
iter=mapStudent.lower_bound(2);
返回的是下界的迭代器
cout<<iter->second<<endl;
iter
返回的是下界的迭代器
cout<<iter->second<<endl;
iter=mapStudent.upper_bound(2);
返回的是上界的迭代器
cout<<iter->second<<endl;
iter=mapStudent.upper_bound(3);
返回的是上界的迭代器
cout<<iter->second<<endl;
pair<map<int,string>::iterator,map<int,string>::iterator>mapPair;
mapPair
if(mapPair.first==mapPair.second)
{
cout<<"Do
}
else
cout<<"Find"<<endl;
}