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

How to use sort function in c++

下次还敢
下次还敢Original
2024-04-26 15:18:13386browse

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.

How to use sort function in c++

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,

  • first and last are iterators representing the range of containers to be sorted.
  • comp is an optional comparison function used to specify the sorting order.

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 sort function only sorts contiguous memory areas, so the container must be a sequential container, such as array, vector, list, etc.
  • The sorting algorithm is performed in-place, which means that it directly modifies the contents of the container.
  • If the containers contain identical elements, the sort function rearranges them based on the behavior of the comparison function.

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!

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