c++ map 根据值的顺序返回排好的键值数组

来源:互联网 发布:2016淘宝美工有前途吗 编辑:程序博客网 时间:2024/06/06 12:27

在编程过程中遇到需要利用到这个的地方,虽然我们可以直接把map值读出来手动排序,但是代码的美观程度,简介程度与性能就可以下降了,通过查阅资料在算法头文件中找到了可以提供相关实现的方法,这算是一个小技巧,可以留作备用。


#include "algorithm"#include "vector"#include "string"using namespace std;typedef pair<string, int> PAIR;bool cmp_by_value(const PAIR& lhs, const PAIR& rhs){    return lhs.second < rhs.second;}std::vector<std::string> Convert_Util::sortMapByValue(std::map<std::string,int> sourceMap){    vector<PAIR> name_score_vec(sourceMap.begin(), sourceMap.end());    sort(name_score_vec.begin(), name_score_vec.end(), cmp_by_value);    vector<string> returnList;    for (int i = 0; i != name_score_vec.size(); ++i)    {        returnList.push_back(name_score_vec[i].first );    }    return returnList;}


0 0
原创粉丝点击