Home >Backend Development >C++ >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>
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>
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!