std::sort如何确定排序依据?
How does std::sort determine the sorting basis?
我有以下代码
#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
。
pair数组排序后,print_pairii
显示-3 4 5 40
,意思是排序是按照pair的第一个元素进行的。
为什么会出现这种情况而不是第二个元素的基础?
从这个意义上说,排序是如何工作的?
因为在没有指定比较器的情况下使用 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.
将其分解成它的组成部分很有用。
std::pair
按字典顺序进行比较,正如您刚刚看到的:https://en.cppreference.com/w/cpp/utility/pair. std::sort
compares (all types) using operator<
by default: https://en.cppreference.com/w/cpp/algorithm/sort。将这两个放在一起,然后按第一个元素然后第二个元素的递增顺序对对进行排序。
Why does this happen instead of the basis of the second element? How does sort work in this sense?
因为默认情况下 std::sort
将排序 std::pair::first
然后 std::pair::second
。
如果您想通过第二个元素排序,您必须提供自定义比较运算符。类似于:
sort(p, p + 4,
[](const std::pair<int, int> &x, const std::pair<int, int> &y) {
return x.second < y.second;
});
我有以下代码
#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
。
pair数组排序后,print_pairii
显示-3 4 5 40
,意思是排序是按照pair的第一个元素进行的。
为什么会出现这种情况而不是第二个元素的基础? 从这个意义上说,排序是如何工作的?
因为在没有指定比较器的情况下使用 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.
将其分解成它的组成部分很有用。
std::pair
按字典顺序进行比较,正如您刚刚看到的:https://en.cppreference.com/w/cpp/utility/pair. std::sort
compares (all types) using operator<
by default: https://en.cppreference.com/w/cpp/algorithm/sort。将这两个放在一起,然后按第一个元素然后第二个元素的递增顺序对对进行排序。
Why does this happen instead of the basis of the second element? How does sort work in this sense?
因为默认情况下 std::sort
将排序 std::pair::first
然后 std::pair::second
。
如果您想通过第二个元素排序,您必须提供自定义比较运算符。类似于:
sort(p, p + 4,
[](const std::pair<int, int> &x, const std::pair<int, int> &y) {
return x.second < y.second;
});