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>
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>
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>
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!