Search code examples
c++sorting

How to use std::sort to sort an array in C++


How to use standard template library std::sort() to sort an array declared as int v[2000];

Does C++ provide some function that can get the begin and end index of an array?


Solution

  • In C++0x/11 we get std::begin and std::end which are overloaded for arrays:

    #include <algorithm>
    
    int main(){
      int v[2000];
      std::sort(std::begin(v), std::end(v));
    }
    

    If you don't have access to C++0x, it isn't hard to write them yourself:

    // for container with nested typedefs, 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;
    }