The sort() function in C sorts the elements in the sequence in ascending order. The syntax is: sort(first, last, comp). Parameters include: first (an iterator pointing to the first element in the sequence), last (an iterator pointing to the position after the last element in the sequence), comp (optional comparator, default is ascending order). The sort() function modifies the sequence and returns no value. With custom comparators, the sort order can be customized.
Usage of sort() function in C
sort() function is used in C standard library to sort A function that sorts the elements of a sequence (such as an array or vector) in ascending order. It operates on sequences by moving elements to the correct positions so that they are sorted in some order.
Syntax
<code class="cpp">void sort(InputIterator first, InputIterator last, Compare comp = less<T>());</code>
Parameters
Return value
The sort() function does not return any value, but modifies the sequence by reference.
Example
Sort an array
<code class="cpp">int arr[] = {5, 3, 1, 2, 4}; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n);</code>
Sort a vector
<code class="cpp">vector<int> v = {5, 3, 1, 2, 4}; sort(v.begin(), v.end());</code>
Custom Sort Comparator
The sort() function allows you to customize the sort order by providing a custom comparator. Here is an example to sort a string in descending order:
<code class="cpp">struct compare_strings { bool operator() (const string& a, const string& b) { return a > b; } }; vector<string> words = {"apple", "banana", "cherry"}; sort(words.begin(), words.end(), compare_strings());</code>
By providing your own comparator, you can sort the sequence by any logic you want.
The above is the detailed content of How to use sort in c++. For more information, please follow other related articles on the PHP Chinese website!