C++ Sort Function: Complete Guide & Examples
The sort function in C++ is used to sort elements in a container. To use the sort function, you need to include the header file and the elements in the container must support comparison operations.
Below is the basic usage of the sort function:
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6};
// 对vec中的元素进行升序排序
std::sort(vec.begin(), vec.end());
// 输出排序后的结果
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
In the example above, we use the sort function to sort the elements in a vector container in ascending order. The sort function takes two parameters, the first being the starting position of the element range to be sorted, and the second being the ending position of the element range to be sorted.
To sort elements of a custom type, a comparison function needs to be provided, which can be implemented using a lambda expression or by overloading comparison operators. For example, for a custom structure like Student, the sort function can be used like this:
#include <algorithm>
#include <vector>
struct Student {
std::string name;
int score;
};
int main() {
std::vector<Student> students = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 78}};
// 对students中的元素按照score进行升序排序
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.score < b.score;
});
// 输出排序后的结果
for (const Student& student : students) {
std::cout << student.name << " " << student.score << std::endl;
}
return 0;
}
In the example above, we use a lambda expression to define a comparison function to sort the scores of students in ascending order within the Student structure.