10-2
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.
//"median.h"
#ifndef GUARD_MEDIAN_H
#define GUARD_MEDIAN_H
#include <vector>
#include <algorithm>
#include <stdexcept>
using namespace std;
template <class T, class In>
T median(In beg, In end)
{
vector<T> v(beg, end);
typedef typename vector<T>::size_type vec_sz;
vec_sz size = v.size();
if (size == 0)
throw domain_error("median of an empty input!");
sort(v.begin(), v.end());
vec_sz mid = size / 2;
return size % 2 == 0 ? (v[mid] + v[mid + 1]) / 2 : v[mid];
}
#endif // GUARD_MEDIAN_H
//"main.cpp"
#include "median.h"
#include <iostream>
using std::vector;
using std::cin;
using std::cout;
using std::endl;
int main()
{
vector<int> v;
int data;
int a[5];
size_t i = 0;
cout << "input integers:" << endl;
while (cin >> data)
{
v.push_back(data);
*(a + i++) = data;
}
cout << "vector<int>:" << median<int>(v.begin(), v.end()) << endl;
cout << "int array:" << median<int>(a, a + i) << endl;
system("pause");
}