Question: How can I use the C standard template library's std::sort() to arrange an array in ascending order?
<code class="cpp">int v[2000];</code>
Answer: In C 11, you can utilize two convenient functions:
<code class="cpp">std::sort(std::begin(v), std::end(v));</code>
Additional Question: Does C have a way to determine the start and end positions of an array?
Answer: Yes, in C 11, std::begin and std::end are overloaded for arrays.
<code class="cpp">std::sort(std::begin(v), std::end(v));</code>
If you're using an earlier version of C , you can create your own versions of begin and end:
Non-const:
<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(); }</code>
Const:
<code class="cpp">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(); }</code>
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>
The above is the detailed content of How to Use std::sort to Order an Array in C ?. For more information, please follow other related articles on the PHP Chinese website!