This question already has an answer here:
这个问题在这里已有答案:
- Sort based on multiple things in C++ 5 answers
基于C ++ 5答案中的多个事物进行排序
So basically, I'm trying to sort a vector of struct Entry
(each Entry
has a string word
and an int count
) by the values of the int
s. I managed to do that via an inline lambda expression:
所以基本上,我试图通过int的值对struct Entry的向量(每个Entry有一个字符串字和一个int计数)进行排序。我设法通过内联lambda表达式来做到这一点:
vector<Entry*> entries(old); //make copy of old vector
std::stable_sort(entries.begin(), entries.end(), [] (const Entry *lhs, const Entry *rhs){
return (lhs->count > rhs->count);
});
However, the problem I have now is, if two or more Entry
s have the same count
, I need to sort those in alphabetical order. Is it possible to use another lambda expression somewhere in there, or is there another way to do this? Thanks!
但是,我现在遇到的问题是,如果两个或多个Entrys具有相同的计数,我需要按字母顺序对它们进行排序。可以在那里的某个地方使用另一个lambda表达式,还是有另一种方法可以做到这一点?谢谢!
1 个解决方案
#1
The solution is pretty simple:
解决方案非常简单:
std::stable_sort(entries.begin(), entries.end(),
[] (const Entry *lhs, const Entry *rhs)
{
if( lhs->count != rhs->count )
return lhs->count > rhs->count;
else
return lhs->word > rhs->word;
});
#1
The solution is pretty simple:
解决方案非常简单:
std::stable_sort(entries.begin(), entries.end(),
[] (const Entry *lhs, const Entry *rhs)
{
if( lhs->count != rhs->count )
return lhs->count > rhs->count;
else
return lhs->word > rhs->word;
});