Search code examples
c++

(accelerated C++) chapter managing memory


I am going through accelerated C++ and I am stuck in exercise 10.3:

Rewrite the median function from §8.1.1/140 so that we can call it with either a vector or a built-in array. The function should allow containers of any arithmetic type.

The code for above question is given below:

template <class T>
 T median( vector<T> v)
 {
    typedef typename vector<T>::size_type vec_sz;
     vec_sz size = v.size();
     if( size == 0 )
     {
         throw domain_error(" median of an empty vector");
     }
     sort( v.begin(), v.end() );
     vec_sz mid = size /2;
     return size%2 == 0 ? ( v[mid]+v[mid+1])/2 : v[mid] ;
 }

I have no clue what to do next.


Solution

  • The comments from juanchopanza and Mooing Duck with hints on iterators is probably the right approach for the book exercise. However, in a practical application, I may instead write a wrapper function that would accept an array, and call the original function that accepts the vector:

    template <class T, size_t N>
    T median (const T (&a)[N])
    {
        return median(std::vector<T>(a, a+N));
    }