按key
//自定义map的key
typedef struct UrlKey
{
uint64_t dwBussID;
uint64_t dwVersion;
uint64_t dwHashUrl;
}UrlKey;
//自定义map的value
typedef struct UrlValue
{
string strUrl;
}UrlValue;
//map的比较函数
struct cmp_key
{
bool operator()(const UrlKey &k1, const UrlKey &k2)const
{
if(k1.dwBussID != k2.dwBussID)
{
return k1.dwBussID < k2.dwBussID;
}
if(k1.dwVersion != k2.dwVersion)
{
return k1.dwVersion < k2.dwVersion;
}
if(k1.dwHashUrl != k2.dwHashUrl)
{
return k1.dwHashUrl < k2.dwHashUrl;
}
return false;
}
};
map<UrlKey, UrlValue, cmp_key> UrlMap;
按value:
这个就比较麻烦了。大致分为两种方法:
1:再建一个新的map和原先map的key和value正好反过来,但前提是原先的value没有重复。
2:将map转换成vector<pair<> >来排序。
#include <bits/stdc++.h>
using namespace std;
map<int,int> MMP;
struct CmpByValue {
bool operator()(const pair<int,int>& lhs, const pair<int,int>& rhs)const {
return lhs.second < rhs.second;
}
};
int main(){
MMP.insert(make_pair(1,4));
MMP.insert(make_pair(2,3));
MMP.insert(make_pair(3,2));
MMP.insert(make_pair(4,1));
vector< pair<int,int> > V(MMP.begin(),MMP.end());
sort(V.begin(),V.end(),CmpByValue());
for(int i=0 ; i<V.size() ; ++i){
printf("%d\n",V[i].second);
}
return 0;
}