对map进行key 和value的排序
对map的value从小到大排序
正常的map默认按照key值排序,而map又没有像vector一样的sort()函数,那么如果将map按照value值排序呢,方法如下
方法. 将map中的key和value分别存放在一个pair类型的vector中,然后利用vector的sort函数排序:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
bool cmp(const pair<int,int> &p1,const pair<int,int> &p2)//要用常数,不然编译错误
{
return p1.second<p2.second;
}
int main(void)
{
map<int,int> mp;
mp[1]=4;
mp[2]=3;
mp[3]=2;
mp[4]=1;
vector<pair<int,int> > arr;
for (map<int,int>::iterator it=mp.begin();it!=mp.end();++it)
{
cout<<it->first<<'\t'<<it->second<<endl;
arr.push_back(make_pair(it->first,it->second));
}
sort(arr.begin(),arr.end(),cmp);
for (vector<pair<int,int> >::iterator it=arr.begin();it!=arr.end();++it)
{
cout<<it->first<<'\t'<<it->second<<endl;
}
return 0;
}
map的成员函数:三个成员函数
- insert
- erase
- find
- rbegin() 返回一个指向map尾部的逆向迭代
- rend() 返回一个指向map头部的逆向迭代器
- size() 返回map中元素的个数
- swap() 交换两个map
inser的四种方法:最常用的还是make_pair这种
1.mapStudent.insert(pair<string, string>("r000", "student_zero"));
2.mp.insert(make_pair(i, i));
3.mapStudent["r123"] = "student_first";
4.maplive.insert(map<int,string>::value_type(321,"hai"));
erase
//删除元素
map<string,int>::iterator strmap_iter1 = strMap.begin();
for(;strmap_iter1 !=strMap.end();strmap_iter1++)
{
cout<<strmap_iter1->first<<' '<<strmap_iter1->second<<endl;
}
cout<<endl;
strMap.erase(iter1);//删除一个条目
strMap.erase(string("jason"));//根据键值删除
--------------------------------------------------------------------------------------
//迭代器刪除
iter = mapStudent.find("r123");
mapStudent.erase(iter);
//用關鍵字刪除
int n = mapStudent.erase("r123");//如果刪除了會返回1,否則返回0
//用迭代器範圍刪除 : 把整個map清空
mapStudent.erase(mapStudent.begin(), mapStudent.end());
//等同於mapStudent.clear()
find
map<int, int>::iterator it_find;
it_find = mp.find(0);
if (it_find != mp.end()){
it_find->second = 20;
}else{
printf("no!\n");
}
------------------------------------------------------------------------------
iter = mapStudent.find("r123");
if(iter != mapStudent.end())
cout<<"Find, the value is"<<iter->second<<endl;
else
cout<<"Do not Find"<<endl;
----------------------------------------------------------------
//查找元素
map<string,int>::iterator iter1;
//面对关联式容器,应该使用其所提供的find函数来搜索元素,会比使用STL算法find()更有效率。因为STL算法find()只是循环搜索。
iter1 = strMap.find(string("mchen"));
if(iter1 == strMap.end())
cout<<"mchen no fount"<<endl;
cout<<endl;