'(accelerated C++) chapter managing memory
I am going through accelerated C++ and I am stuck in exercise 10.3 and I have literally no clue how to even start. I would like to mention here that its not homework exercise and I am reading it just to gain confidence in C++ . The question is shown below .
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. Any help or criticism will be beneficial to me. Thanks and regards
Solution 1:[1]
I realize that the question is quite old but as I'm currently working through the same book I figured I would post my solution in the hope that it may help someone else.
// median.hpp
#include <algorithm> // sort
#include <stdexcept> //domain_error
#include <vector>
template <typename T, typename In>
T median(In begin, In end)
{
if (begin == end)
throw std::domain_error("median of an empty vector");
std::vector<T> v { };
while (begin != end)
{
v.push_back(*begin++);
}
std::sort(v.begin(), v.end());
typedef typename std::vector<T>::size_type vec_sz;
vec_sz vSize = v.size();
vec_sz mid = vSize/2;
return vSize % 2 == 0 ? ( v[mid] + v[mid - 1] ) / 2
: v[mid];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vilhelmo De Okcidento |
