Home > Backend Development > C++ > body text

How to Use std::sort for Array Sorting in C ?

DDD
Release: 2024-10-23 19:01:31
Original
493 people have browsed it

How to Use std::sort for Array Sorting in C  ?

How to Utilize std::sort for Array Sorting in C

Sorting an array using the C standard template library's std::sort function can be done as follows:

<code class="cpp">int main() {
  int v[2000];
  std::sort(v, v + 2000);  // Sort the array
}</code>
Copy after login

However, C 0x/11 introduced std::begin and std::end functions, simplifying the process:

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

int main() {
  int v[2000];
  std::sort(std::begin(v), std::end(v));  // Sort the array
}</code>
Copy after login

If std::begin and std::end are not available, they can be defined as:

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

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

// Const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c) {
  return c.begin();
}

template<class Cont>
typename Cont::const_iterator end(Cont const& 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 Use std::sort for Array Sorting 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
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!