C++ Sort Function: Guide with Examples
In C++, the sort function is used to sort elements in a container, either in default ascending order or according to a custom sorting rule.
Here is a basic example of sorting integer elements in a vector container.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {4, 2, 1, 5, 3};
// 使用sort函数对容器中的元素进行排序
std::sort(numbers.begin(), numbers.end());
// 打印排序后的结果
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
If you want to sort in descending order, you can use greater
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
If you want to customize the sorting rules, you can use a lambda expression as the third parameter passed to the sort function, for example sorting by the absolute value of numbers.
std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return abs(a) < abs(b);
});
This allows for sorting the elements in the container based on a custom sorting rule.