#include <iostream>
using namespace std;
#include <map>
#include <string>
template<typename T> void PrintContainer( T container )
{
T::iterator iter = container.begin();
for( ; iter != container.end() ; ++iter)
{
cout<<iter->first<<" , "<<iter->second<<endl;
}
cout<<endl;
}
void main()
{
//创建一个新的map,其中不含任何元素
map<int,string> map1; // int 类型的key , string类型的value
map1[0] = "Yao";
map1[2] = "Shun";
map1[1] = "Yu";
PrintContainer(map1);
//以op为准则生成一个空的map
map<int,string,greater<int>> map2; // less<key>:以key为准则升序
map2[0] = "Tom"; // greater<key>:以key为准则降序
map2[3] = "Jerry";
map2[2] = "Rose";
map2[1] = "Jacky";
map2[5] = "Lily";
map2[4] = "lucy";
map2[6] = "David";
PrintContainer(map2);
//根据一个已有的map产生一个新的map
map<int,string>map3(map1); //排序准则不同的两种map容器,
PrintContainer(map3); //不能互相产生新的对象
//由[beg,end)区间内的元素生成一个新的map
map<int,string,greater<int>> map4(++(map2.begin()),--(map2.end()));
PrintContainer(map4);
map的析构函数
//map1.~map();
//map2.~map();
//map3.~map();
//map4.~map();
cout<<"map1中元素个数为:"<<map1.size()<<endl;
cout<<"map2中元素个数为:"<<map2.size()<<endl;
cout<<"map3中元素个数为:"<<map3.size()<<endl;
cout<<"map4中元素个数为:"<<map4.size()<<endl;
//====map的find函数:在容器中根据key寻找某个元素====
int key = 8;
map<int,string,greater<int>>::iterator iter = map4.find(key);
if(iter != map4.end() )
cout<<"找到的数据为:"<<iter->first<<" , "<<iter->second<<endl;
else
cout<<"不存在key为"<<key<<"的元素"<<endl;
//====在容器中根据value寻找某个元素====
string value = "Jerryr";
bool bIsFind = false;
map<int,string,greater<int>>::iterator serach = map4.begin();
for( ; serach!= map4.end() ; ++serach)
{
if( value == serach->second )
{
bIsFind = true;
cout<<value<<"所对应的key为:"<<serach->first<<endl;
}
}
if(!bIsFind)
cout<<"容器中没有value为"<<value<<"的元素"<<endl;
//====count( n )函数返回容器中key为n的元素个数====
int n = 2 ;
cout<<"map4中key为"<<n<<"的元素的个数为:"<<map4.count(n)<<endl;
//============lower_bound(key)函数============
cout<<"========lower_bound(key)函数========"<<endl;
map<int,string,greater<int>>::iterator index;
index = map4.lower_bound(3); //返回键值>=3的第一个元素的迭代器
cout<<index->first<<" , "<<index->second<<endl;
//============upper_bound(key)函数============
cout<<"========upper_bound(key)函数========"<<endl;
map<int,string,greater<int>>::iterator big;
big = map4.upper_bound(3); //返回键值>3的第一个元素的迭代器
cout<<big->first<<" , "<<big->second<<endl;
//========map的insert(element)函数===========
cout<<"========map的insert(element)函数==========="<<endl;
map4.insert( map<int,string,greater<int>>::value_type(0,"John"));
map4.insert( pair<int,string>(6,"Mogen") );
map4.insert( make_pair(7,"Sniper") );
PrintContainer(map4);
//=====清空map1内的数据
map1.clear();
cout<<"map1中元素个数为:"<<map1.size()<<endl;
system("pause");
}
map的用法
最新推荐文章于 2023-03-27 20:16:15 发布