gpt4 book ai didi

c++ - c++ - 如何在c++中按降序对基于第二个元素的对列表进行排序

转载 作者:行者123 更新时间:2023-12-01 15:13:31 26 4
gpt4 key购买 nike

我想知道是否有办法根据第二个元素对我的对列表进行排序。这是一个代码:

std::list<std::pair<std::string, unsigned int>> words;

words.push_back(std::make_pair("aba", 23);
words.push_back(std::make_pair("ab", 20);
words.push_back(std::make_pair("aBa", 15);
words.push_back(std::make_pair("acC", 8);
words.push_back(std::make_pair("aaa", 23);

我想根据整数元素按降序对列表单词进行排序,以便我的列表如下所示:
<"aba", 23>,<"aaa", 23>,<"ab", 20>,<"aBa", 15>,<"acC", 8>

此外,是否可以按第一个和第二个元素对它们进行排序,以便它首先按第二个元素(按整数值)排序,然后如果有两个或更多对具有相同的第二个元素(即相同的整数值),然后它将根据按字母顺序排列的第一个元素对它们进行排序,然后上面排序列表中的前 2 对将交换,因此:
<"aaa", 23>,<"aba", 23>,<"ab", 20>,<"aBa", 15>,<"acC", 8>

最佳答案

I would like to sort my list words based in the integer element in decreasing order



排序谓词必须返回 true如果第一个元素(即第一对)在您建立的顺序中在第二个元素之前传递:
words.sort([](auto const& a, auto const& b) {
return a.second > b.second;
});

由于您想按降序对列表进行排序,因此对 a将在 b 之前如果它的第二个元素(即 int )大于 b的第二个元素。

请注意 std::sort() 不适用于对 std::list 进行排序因为它需要随机访问迭代器,但 std::list只提供双向迭代器。

is it possible to sort them by both the first and second element such that it sorts by the second elements first (by integer value), and then if there's two or more pairs with the same second element (i.e. same integer value), then it will sort those based on the first element in alphabetical order



再次假设 int 的降序元素,当两个 int 都使用对的第二个元素时元素是一样的:
   lst.sort([](auto const& a, auto const& b) {
if (a.second > b.second)
return true;
if (a.second < b.second)
return false;
return a.first < b.first;
});

或者更简洁感谢 std::tie() :
lst.sort([](auto const& a, auto const& b) {
return std::tie(b.second, a.first) < std::tie(a.second, a.first);
});

关于c++ - c++ - 如何在c++中按降序对基于第二个元素的对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60034357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com