gpt4 book ai didi

c++ - std::sort如何确定排序依据?

转载 作者:行者123 更新时间:2023-12-01 14:39:59 26 4
gpt4 key购买 nike

我有以下代码

#include <bits/stdc++.h>                                                                               
using namespace std;

int main () {
pair<int, int> p[4];
p[0] = pair<int, int>(5, 2);
p[1] = pair<int, int>(40, -2);
p[2] = pair<int, int>(-3, 2);
p[3] = pair<int, int>(4, 45);

auto print_pairii = [](pair<int, int> pp[]) {
for (int i = 0; i < 4; i++) {
cout << pp[i].first << " ";
}
cout << endl;
};


print_pairii(p);

sort(p, p + 4);

print_pairii(p);
return 0;
}

第一个 print_pairii显示为 5 40 -3 4
在对对数组进行排序之后, print_pairii显示为 -3 4 5 40,这意味着排序是基于对的第一个元素进行的。

为什么会发生这种情况而不是第二个要素的基础?
从这个意义上说,排序是如何工作的?

最佳答案

因为在不指定比较器的情况下使用 std::sort 时,将使用operator<比较元素。

1) Elements are compared using operator<.



并且重载的 operator< for std::pair 首先比较第一个元素,然后比较第二个元素(如果第一个元素相等)。

Compares lhs and rhs lexicographically, that is, compares the first elements and only if they are equivalent, compares the second elements.

关于c++ - std::sort如何确定排序依据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59807946/

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