Home  >  Article  >  Backend Development  >  How to: Sort an Array Using std::sort in C

How to: Sort an Array Using std::sort in C

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 21:00:02841browse

How to: Sort an Array Using std::sort in C

Sorting Array Using std::sort in C

In C , the standard template library provides the std::sort() function to efficiently sort elements in an array. For an array declared as int v[2000], the following code snippet demonstrates how to use std::sort() to achieve this:

<code class="cpp">#include <algorithm>

int main() {
  int v[2000];
  std::sort(std::begin(v), std::end(v));
}</code>

However, the std::begin() and std::end() functions introduced in C 0x/11 are essential for this approach. These functions return iterators representing the beginning and end of a given container, including arrays.

If you don't have access to C 0x, it's possible to define these functions yourself:

Begin function for non-const containers:

<code class="cpp">template<class Cont>
typename Cont::iterator begin(Cont& c) {
  return c.begin();
}</code>

End function for non-const containers:

<code class="cpp">template<class Cont>
typename Cont::iterator end(Cont& c) {
  return c.end();
}</code>

Begin function for const containers:

<code class="cpp">template<class Cont>
typename Cont::const_iterator begin(Cont const& c) {
  return c.begin();
}</code>

End function for const containers:

<code class="cpp">template<class Cont>
typename Cont::const_iterator end(Cont const& c) {
  return c.end();
}</code>

Overloads for C-style arrays:

<code class="cpp">template<class T, std::size_t N>
T* begin(T (&arr)[N]) {
  return &arr[0];
}

template<class T, std::size_t N>
T* end(T (&arr)[N]) {
  return arr + N;
}</code>

By using these functions, you can seamlessly sort an array using std::sort() in C .

The above is the detailed content of How to: Sort an Array Using std::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