Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-10-23 21:00:02
Original
840 people have browsed it

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

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

End function for non-const containers:

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

Begin function for const containers:

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

End function for const containers:

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

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

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!

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!