How to use the C++ sort function?
In C++, the sort function from the standard library can be used for sorting operations. The sort function takes in an iterator pointing to the first element of the container (such as an array, vector, or list) and an iterator pointing to the last element of the container, along with an optional comparison function to specify the sorting order.
Here is an example of sorting using the sort function:
#include <iostream>
#include <vector>
#include <algorithm>
bool compare(int a, int b) {
return a < b; // 以升序排序
}
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 3};
std::sort(numbers.begin(), numbers.end(), compare);
std::cout << "排序后的结果:";
for (int number : numbers) {
std::cout << number << " ";
}
std::cout << std::endl;
return 0;
}
In the above example, we have defined a comparison function called “compare” to specify the order of sorting. The compare function returns true to indicate that the first parameter is less than the second parameter, resulting in ascending order. We then pass the “numbers” container to the “sort” function for sorting. Finally, we use a loop to output the sorted results.
The output is: the sorted result is 1 2 3 5 8, which means the result is in ascending order.
Note that if a comparison function is not provided as the third parameter of the sort function, the < operator will be used for sorting.