簡體   English   中英

排序 function 無法正常工作(c++)

[英]sort function does not work properly (c++)

我正在嘗試對vector<pair<string, int>> list進行排序,但是排序對我來說似乎無法正常工作。

對的向量包含字符串的人名和 integer 的年份。

任務是按年份對列表進行排序,如果它們相同,則按名稱按字母順序排序。

輸入:

John 20
Tom  25
Mark 20

output 應該是

John 20
Mark 20
Tom  25

我的程序沒有改變任何東西,我找不到問題所在。 我會很感激一些幫助。

我的代碼:

vector<pair<string, int>> list;
list.push_back({ "John", 20 });
list.push_back({ "Tom",  25 });
list.push_back({ "Mark", 20 });

sort(list.begin(), list.end(), [](pair<string, int>& a, pair<string, int>& b)
    {
        if (a.second < b.second)
            return a.second > b.second;
        return a.first < b.first;
    }
);

for (const auto& x : list)
    cout << x.first << " " << x.second << endl;

如果a.second < b.secondtrue ,則您需要比較函子返回true ,但

if (a.second < b.second)         // if this is `true`
    return a.second > b.second;  // this will always be `false`

糾正它的一種簡單方法是制作一個自上而下的過濾器,如下所示:

sort(list.begin(), list.end(), [](const auto& a, const b& rhs){ 
    if(a.second < b.second) return true;
    if(b.second < a.second) return false; // note: the operands are flipped

    // if reaching here, a.second and b.second are considered equal (which is
    // not the same as `==` in cases where the operands are floating points)

    return a.first < b.first; // compare the remaining member
});

使用std::tie可以使上述內容變得更簡單:

sort(list.begin(), list.end(), [](const auto& a, const auto& b){ 
    return std::tie(a.second, a.first) < std::tie(b.second, b.first); 
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM