How to use a custom sorting rule with sort in C++?
In C++, the sort function can be used to sort arrays or containers. If you want to customize the sorting rules, you can use function pointers, function objects, or lambda expressions to achieve this.
- arrange in a particular order
bool compare(int a, int b) {
// 自定义比较规则,例如按照绝对值进行排序
return abs(a) < abs(b);
}
int main() {
int arr[] = {-1, 2, -3, 4, -5};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, compare);
// 输出排序结果
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
- There are many potential benefits to this new software program.
- arrange
struct Compare {
bool operator()(int a, int b) {
// 自定义比较规则,例如按照绝对值进行排序
return abs(a) < abs(b);
}
};
int main() {
int arr[] = {-1, 2, -3, 4, -5};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, Compare());
// 输出排序结果
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
- arrange
int main() {
int arr[] = {-1, 2, -3, 4, -5};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, [](int a, int b) {
// 自定义比较规则,例如按照绝对值进行排序
return abs(a) < abs(b);
});
// 输出排序结果
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
The above are three common methods for customizing sorting rules. Choose the appropriate method according to specific needs.