Home  >  Article  >  Backend Development  >  How to use sort in c++

How to use sort in c++

下次还敢
下次还敢Original
2024-05-01 10:45:24987browse

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.

How to use sort in c++

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

  • first: points to the first in the sequence Iterator of elements.
  • last: An iterator pointing to one position after the last element in the sequence.
  • comp: Optional comparator used to determine the order of elements. Defaults to less() (sorts elements in ascending order).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn