根据多种条件对结构进行分类

Sorting structs based on multiple conditions?

本文关键字:结构 分类 条件      更新时间:2023-10-16

基本上,我正在尝试按int s的值对struct Entry的向量(每个Entry都有string wordint count)。我设法通过inline 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);
});

但是,我现在遇到的问题是,如果两个或多个Entry S具有相同的count,则我需要按字母顺序排序。是否可以在其中某个地方使用另一个Lambda表达式,还是有其他方法可以这样做?谢谢!

解决方案非常简单:

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;
 });