Home >Backend Development >C++ >How to use sort function in c++
The sort function in C is a useful STL algorithm library function used to sort elements in a container. Its basic syntax is: `sort(Iterator first, Iterator last)`, where first and last are iterators that define the starting and ending positions of the sequence. By default, the sort function sorts in ascending order, but you can customize the sorting by providing a comparison function or overloading `operatorf33897c4d4f96d09eebbd70cee26ddfa header file, so you need to include this header file before using it.
The basic syntax of the sort function is as follows:
cpp
#include <algorithm> #include <vector> std::sort(Iterator first, Iterator last);Here, first and last are iterators, which define the starting and ending positions of the sequence to be sorted. Note that the last iterator points to the next element at the "end position" of the sequence, so the actual range of the sequence is [first, last).
The sort function sorts elements in ascending order by default. If you need to sort objects of a custom type, you may need to provide a comparison function or overload operator086b72f98ad39ed65ed991d31f15ba7b:
cpp
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {5, 2, 8, 1, 9}; std::sort(numbers.begin(), numbers.end()); for (int num : numbers) { std::cout << num << ' '; } return 0; }This program will output: 1 2 5 8 9, this is the result of the elements in the numbers vector being arranged in ascending order.
If you need to sort objects of a custom type, you need to provide a comparison function or overload operator<. For example, suppose you have a Person class that has an age member variable, and you want to sort Person objects by age:
cpp
#include <iostream> #include <vector> #include <algorithm> class Person { public: std::string name; int age; Person(const std::string& name, int age) : name(name), age(age) {} // 重载 operator< 以便 sort 可以使用 bool operator<(const Person& other) const { return age < other.age; } }; int main() { std::vector<Person> people = { {"Alice", 30}, {"Bob", 20}, {"Charlie", 25} }; std::sort(people.begin(), people.end()); for (const auto& person : people) { std::cout << person.name << ": " << person.age << std::endl; } return 0; }This program will output each person's age in ascending order Name and age. Note that we overload operator< so that the sort function knows how to compare Person objects. If you don't want to overload operator
The above is the detailed content of How to use sort function in c++. For more information, please follow other related articles on the PHP Chinese website!