您的位置:首页 > 产品设计 > UI/UE

map按value排序的问题

2016-11-30 00:17 162 查看
参考 http://blog.csdn.net/acidgl8757/article/details/17416439

实际上对map是红黑树实现的非线性的容器,不能直接使用迭代的sort算法对map中的value进行排序。
所以需要将map的pair<key,value> 转化到vector之类的线性容器之中实现排序功能。
而且排序的结果存放在你转化的容器里面,对map的原值不会产生影响。


typedef pair<string, int> PAIR;
bool operator< (const PAIR& lhs, const PAIR& rhs) {
return lhs.second < rhs.second;
}

static bool com_map_value(const PAIR& lhs, const PAIR& rhs)
{
return lhs.second < rhs.second;
}

int main() {
map<string, int> name_score_map;
name_score_map["LiMin"] = 90;
name_score_map["ZiLinMi"] = 79;
name_score_map["BoB"] = 92;
name_score_map.insert(make_pair("Bing",99));
name_score_map.insert(make_pair("Albert",86));
//把map中元素转存到vector中
vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());
sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());
// sort(name_score_vec.begin(), name_score_vec.end(), cmp_by_value);
for (int i = 0; i != name_score_vec.size(); ++i) {
cout << name_score_vec[i] << endl;
}
return 0;
}


注意:在windows中 2种sort的回调函数都行

但是在linux 中 要选择 类形式的 或者 在com_map_value设置成static的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: