根据多种条件对结构进行排序? [重复]

时间:2022-12-28 19:06:10

This question already has an answer here:

这个问题在这里已有答案:

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 ints. 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 Entrys 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;
 });