开发者

Using a type parameter and a pointer to the same type parameter in a function template

开发者 https://www.devze.com 2022-12-28 07:47 出处:网络
I\'ve written a template function to determine the median of any vector o开发者_如何学Pythonr array of any type that can be sorted with sort.The function and a small test program are below:

I've written a template function to determine the median of any vector o开发者_如何学Pythonr array of any type that can be sorted with sort. The function and a small test program are below:

#include <algorithm>
#include <vector>
#include <iostream>
using namespace::std;

template <class T, class X>
void median(T vec, size_t size, X& ret)
{
    sort(vec, vec + size);
    size_t mid = size/2;
    ret =  size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}

int main()
{
    vector<double> v;
    v.push_back(2); v.push_back(8);
    v.push_back(7); v.push_back(4);
    v.push_back(9);

    double a[5] = {2, 8, 7, 4, 9};

    double r;
    median(v.begin(), v.size(), r);
    cout << r << endl;
    median(a, 5, r);
    cout << r << endl;
    return 0;
}

As you can see, the median function takes a pointer as an argument, T vec. Also in the argument list is a reference variable X ret, which is modified by the function to store the computed median value.

However I don't find this a very elegant solution. T vec will always be a pointer to the same type as X ret. My initial attempts to write median had a header like this:

 template<class T>
 T median(T *vec, size_t size)
 {
      sort(vec, vec + size);
      size_t mid = size/2;
      return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
 }

I also tried:

 template<class T, class X>
 X median(T vec, size_t size)
 {
      sort(vec, vec + size);
      size_t mid = size/2;
      return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
 }

I couldn't get either of these to work. My question is, can anyone show me a working implementation of either of my alternatives?

Thanks for looking!


The idiomatic approach is to use iterators. To enable this, you can derive the return type from the iterator:

template <class I>
typename iterator_traits<I>::value_type median(I start, I finish)
{
    ...
}


I'd do this:

template <class T>
void median( T* vec, size_t size, T& ret )
{
    sort( vec, vec + size );
    size_t mid = size/2;
    ret =  size % 2 == 0 ? ( vec[mid] + vec[mid-1] ) / 2 : vec[mid];
}

template <class T>
void median( vector<T>& vec, T& ret )
{
        median( &*vec.begin(), vec.size(), ret );
}

But that's just me.

0

精彩评论

暂无评论...
验证码 换一张
取 消