Home >Backend Development >C++ >How to Sort Arrays Using std::sort in C ?

How to Sort Arrays Using std::sort in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 21:30:02939browse

How to Sort Arrays Using std::sort in C  ?

Sorting Arrays with std::sort in C

To sort an array declared as int v[2000]; using the std::sort function, simply provide the begin and end iterators of the array. In C 0x/11, this can be achieved with the std::begin and std::end functions which are overloaded for arrays:

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

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

If you don't have access to C 0x, you can implement these functions yourself:

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

template<class Cont>
typename Cont::iterator end(Cont& c){
  return c.end();
}

// overloads for C style arrays
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>

The above is the detailed content of How to Sort Arrays 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