且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

std::sort 对列表如何工作?

更新时间:2023-11-13 23:20:10

自从 operator 是为 std::pair 定义的,它基于 std::pair::first 然后是 std::pair::second (字典序),所以你的代码是作为标准工作的.要根据 std::pair 的第二部分对其进行排序,您可以尝试:

Since operator< is defined for std::pair and it is based on std::pair::first and then std::pair::second (lexicographical), so your code is working as the standard. To sort it based on the second part of the std::pair you can try this:

std::sort(list.begin(), list.end(), [](const std::pair<int, string> &x,
                                       const std::pair<int, string> &y)
{
    return x.second < y.second;
});