Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-10-23 21:30:02
Original
836 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!