Home >Backend Development >C++ >How to use sort function in c++
The sort function in C sorts container elements in place. It accepts a container range and an optional comparison function, and sorts in ascending order by default. Passing a custom function can sort by different rules.
Usage of sort function in C
The sort function is a powerful algorithm in the C standard library, used to Performs an in-place sorting operation on the elements in the container. It takes a container as input and rearranges the values in the container based on a specific comparison function.
Usage
The prototype of the sort function is as follows:
<code class="cpp">void sort(InputIt first, InputIt last, Compare comp = less<>());</code>
Among them,
Sort rules
By default, the sort function uses the std::less<>
comparison function, which will be smaller elements are sorted before larger elements. A custom comparison function can be passed to specify different collations.
For example:
Sort number containers in descending order:
<code class="cpp">#include <vector> #include <algorithm> int main() { std::vector<int> numbers = {3, 1, 5, 2, 4}; std::sort(numbers.begin(), numbers.end(), std::greater<>{}); // 输出:{5, 4, 3, 2, 1} }</code>
Notes
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!