On May 12, 4:37=A0pm, utab <umut.ta...@[EMAIL PROTECTED]
> wrote:
> I was experimenting with a template taking two iterators for the range
> of
> a vector.(Perhaps, it is sth simple and I am missing it because it is
> a
> late hour.) I ran into problems in the compile phase , the code is
> below:
>
> #include <iostream>
> #include <algorithm>
> #include <stdexcept>
> #include <vector>
>
> using std::domain_error;
> using std::sort;
> using std::vector;
>
> template <class T, class Ran>
> T median(Ran b, Ran e)
> {
> =A0 typedef typename vector<T>::size_type vec_sz;
>
> =A0 vec_sz size =3D (e-b)/sizeof(T);
> =A0 if (size =3D=3D 0)
> =A0 =A0 throw domain_error("median of an empty vector");
>
> =A0 sort(b, e);
>
> =A0 vec_sz mid =3D size/2;
>
> =A0 return size % 2 =3D=3D 0 ? (b[mid] + b[mid-1]) / 2 : b[mid];
> }
The C++ compiler is not able to deduce the type "T" from the median()
function call. Since "T" is dependent on the iterator type "Ran", I
would eliminate "T" altogether. Note also that the calculation of
"size" is incorrect - e-b will return the number of positions between
two random access iterators.
Applying these suggestions produces a program like this one:
#include <iostream>
#include <algorithm>
#include <stdexcept>
#include <vector>
#include <iterator>
using std::domain_error;
using std::sort;
using std::vector;
template <class Ran>
typename std::iterator_traits<Ran>::value_type
median(Ran b, Ran e)
{
size_t size =3D e-b;
if (size =3D=3D 0)
throw domain_error("median of an empty vector");
sort(b, e);
size_t mid =3D size/2;
return size % 2 =3D=3D 0 ? (b[mid] + b[mid-1]) / 2 : b[mid];
}
int main()
{
vector<double> vec;
for (int i=3D0; i!=3D10; ++i)
vec.push_back(i);
std::cout << median(vec.begin(), vec.end()) << std::endl;
return 0;
}
Greg


|