我想按ints排序,按递减顺序排列,但如果值相等,则按字符串排序。我有这样的代码,我对地图进行排序,然后将第一个k值写入向量:
map<string, int> m;
vector<string> calc(int k) {
typedef std::function<bool(std::pair<std::string, int>, std::pair<std::string, int>)> Comparator;
Comparator compFunctor =
[](std::pair<std::string, int> p1 ,std::pair<std::string, int> p2)
{
if(p1.second != p2.second){
return p1.second > p2.second;
}else{
return p1.first > p2.first;
}
};
std::set<std::pair<std::string, int>, Comparator> setOfWords(m.begin(), m.end(), compFunctor);
int c = 0;
vector<string> str;
for(auto it = m.begin(); it != m.end(); it++){
if(c >= k){
break;
}
str.push_back(it->first);
c += 1;
}
for(int i = 0; i<str.size(); i++){
cout << str[i] << " ";
}
return str;
}
};然而,它没有排序。
auto cmp = [](std::pair<int,string> const & p1, std::pair<int,string> const & p2)
{
if(p1.second != p2.second){
return p2.second > p1.second;
// }
// return true;
}else{
return p2.first > p1.first;
}
};
std::sort(m.begin(), m.end(), cmp);我也试过了,但它甚至没有编译。它给出了二进制表达式的无效操作数('std::__1::__map_iterator,int>,std::__1::__tree_node,int>,void *> *,long> >和std::__1::__map_iterator,int>,std::__1::__tree_node,int>,void*> *,long> >')
发布于 2018-10-05 07:19:58
它是工作的,当得到排序的结果时,您只应该遍历"setOfWords“而不是"m”。
for(auto it = m.begin(); it != m.end(); it++){发布于 2018-10-05 08:27:45
thing1和thing2比较的一种简单方法。是使用operator <和std::tie通过引用创建一个元组。
using Item = std::pair<std::string, int>;
auto cmp = [](const Item & lhs, const Item & rhs)
{
return std::tie(lhs.second, lhs.first) < std::tie(rhs.second, rhs.first);
}https://stackoverflow.com/questions/52660027
复制相似问题