473,386 Members | 1,779 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

template function to accept vector and array

Dear all,

I have the below template (1) which I would like to implement to accept
either a vector or an array. I thought on it some time and came with a
solution as in (2) , however the call of my implementation is not natural
in the way that I do not supply the vector directly. How can I improve on
that?

(1)
template <class T>
T median(vector<Tv)
{
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];
}

(2)
template <class T>
T median( T*v, int n )
{
size_t sz = n;
if (n == 0)
throw domain_error("median of an empty vector");
sort(v, v+n);
size_t mid = sz/2;
return sz % 2 == 0 ? (v[mid] + v[mid-1]) / 2 : v[mid];
}

calls for (2) are

std::cout << median(a,7) << std::endl; // for array
....
std::cout << median(&(*b.begin()),b.size()) << std::endl; // for vector

Best regards,

Aug 28 '08 #1
3 2528
utab wrote:
Dear all,

I have the below template (1) which I would like to implement to
accept either a vector or an array. I thought on it some time and
came with a solution as in (2) , however the call of my
implementation is not natural in the way that I do not supply the
vector directly. How can I improve on that?

(1)
template <class T>
T median(vector<Tv)
{
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];
}

(2)
template <class T>
T median( T*v, int n )
{
size_t sz = n;
if (n == 0)
throw domain_error("median of an empty vector");
sort(v, v+n);
size_t mid = sz/2;
return sz % 2 == 0 ? (v[mid] + v[mid-1]) / 2 : v[mid];
}

calls for (2) are

std::cout << median(a,7) << std::endl; // for array
...
std::cout << median(&(*b.begin()),b.size()) << std::endl; // for
vector
The best approach would actually be to implement it _once_ by
supplying two iterators to your sequence:

template<class Iterator>
typename Iterator::value_type median(Iterator b, Iterator e)
{
...
}

Instead of doing it with overloading. Then you'll be able to pass
your sequence like so

median(v.begin(), v.end());

median(a, a+7);

I'll leave the implementation to you. It's not that difficult,
really. See the function 'distance' for working with iterators.
It's quite efficient with random-access iterators.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 28 '08 #2
try this:

template<typename Iter>
double median(Iter begin, Iter end)
{
typedef typename iterator_traits<Iter>::difference_type diff_t;
diff_t size = end - begin;
if(0 == size )
throw std::runtime_error("median of empty vector");

sort(begin, end);
diff_t mid = size / 2;
return size % 2 == 0 ? (*(begin+mid-1)+*(begin+mid))/2 : *(begin+mid);
}

int main() {
int arr[] = { 0, 3, 11, 9 };
int arr_size = sizeof(arr)/sizeof(int);
vector<intvec(arr, arr + arr_size);

cout << "arr midian: " << median(arr, arr + arr_size) << endl;
cout << "vec median: " << median(vec.begin(), vec.end()) << endl;

return 0;
}

HTH,
jim

utab 写道:
Dear all,

I have the below template (1) which I would like to implement to accept
either a vector or an array. I thought on it some time and came with a
solution as in (2) , however the call of my implementation is not natural
in the way that I do not supply the vector directly. How can I improve on
that?

(1)
template <class T>
T median(vector<Tv)
{
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];
}

(2)
template <class T>
T median( T*v, int n )
{
size_t sz = n;
if (n == 0)
throw domain_error("median of an empty vector");
sort(v, v+n);
size_t mid = sz/2;
return sz % 2 == 0 ? (v[mid] + v[mid-1]) / 2 : v[mid];
}

calls for (2) are

std::cout << median(a,7) << std::endl; // for array
...
std::cout << median(&(*b.begin()),b.size()) << std::endl; // for vector

Best regards,
Aug 28 '08 #3
then this?

template<typename Iter>
typename iterator_traits<Iter>::value_type median(Iter begin, Iter end)
{
typedef typename iterator_traits<Iter>::difference_type diff_t;
diff_t size = end - begin;
if(0 == size )
throw std::runtime_error("median of empty vector");

size 0 ? sort(begin, end) : sort(end, begin);
diff_t mid = size / 2;
return size % 2 == 0 ? (*(begin+mid-1)+*(begin+mid))/2 : *(begin+mid);
}

int main()
{
int arr[] = { 0, 3, 11, 6 };
int arr_size = sizeof(arr) / sizeof(int);
vector<floatvec(arr, arr + arr_size);

cout << "int arr midian: " << median(arr, arr + arr_size) << endl;
cout << "float vec median: " << median(vec.begin(), vec.end()) << endl;
cout << "inverse: " << median(arr + arr_size, arr) << endl;
return 0;
}

jim

Jim Z. Shi 写道:
try this:

template<typename Iter>
double median(Iter begin, Iter end)
{
typedef typename iterator_traits<Iter>::difference_type diff_t;
diff_t size = end - begin;
if(0 == size )
throw std::runtime_error("median of empty vector");

sort(begin, end);
diff_t mid = size / 2;
return size % 2 == 0 ? (*(begin+mid-1)+*(begin+mid))/2 : *(begin+mid);
}

int main() {
int arr[] = { 0, 3, 11, 9 };
int arr_size = sizeof(arr)/sizeof(int);
vector<intvec(arr, arr + arr_size);

cout << "arr midian: " << median(arr, arr + arr_size) << endl;
cout << "vec median: " << median(vec.begin(), vec.end()) << endl;

return 0;
}

HTH,
jim

utab 写道:
>Dear all,

I have the below template (1) which I would like to implement to
accept either a vector or an array. I thought on it some time and came
with a solution as in (2) , however the call of my implementation is
not natural in the way that I do not supply the vector directly. How
can I improve on that?

(1)
template <class T>
T median(vector<Tv)
{
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];
}

(2)
template <class T>
T median( T*v, int n )
{
size_t sz = n;
if (n == 0)
throw domain_error("median of an empty vector");
sort(v, v+n);
size_t mid = sz/2;
return sz % 2 == 0 ? (v[mid] + v[mid-1]) / 2 : v[mid];
}

calls for (2) are

std::cout << median(a,7) << std::endl; // for array
...
std::cout << median(&(*b.begin()),b.size()) << std::endl; // for vector

Best regards,
Aug 28 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: CoolPint | last post by:
As a self-exercise, I am trying to write a generic Priority Queue, which would store any type and and accept any user-definable "priority" function. After much tinkering, I came up with...
17
by: Jacek Dziedzic | last post by:
Hello! I have a templated class that serves as a simple vector of elements. template <typename T> class simple_vector : public math_object { // ... lots of simple_vector operations // the...
4
by: firegun9 | last post by:
Hello everyone, here is my program: /////////////////////////////// #include <iostream> using namespace std; void multi(double* arrayPtr, int len){ for(int i=0; i<len; i++)...
6
by: Kaba | last post by:
Here is a short snippet of code that does not compile (tested with Vc8 and Comeau). This is because somehow Vector<0gets instantiated, for which the array size goes to 0. However, I don't quite get...
3
by: Hamilton Woods | last post by:
Diehards, I developed a template matrix class back around 1992 using Borland C++ 4.5 (ancestor of C++ Builder) and haven't touched it until a few days ago. I pulled it from the freezer and...
1
by: petschy | last post by:
hello, i've run into an error when qualifying a copy ctor 'explicit'. the strange thing is that i get a compiler error only if the class is a template and declare the variable as X<Zx = y....
272
by: Peter Olcott | last post by:
http://groups.google.com/group/comp.lang.c++/msg/a9092f0f6c9bf13a I think that the operator() member function does not work correctly, does anyone else know how to make a template for making two...
1
by: =?UTF-8?B?SmVucyBNw7xsbGVy?= | last post by:
(I also posted this to boost-user) The BGL implementation of breadth-first search uses a dedicated color map. I had the following idea: Some algorithms don't need to distinguish black/gray,...
5
by: Szabolcs | last post by:
I am looking for a way to generalize the function template below, so that it will work with any type, not just double. Is this at all possible in C++? I'd like to replace double (*fun)(double)...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.