Template Help

I need some help with some homework as classmates are equally stumped and the professor is not responding (yes, bad idea to take this course online but I had no choice as they don't offer it on-campus).

The assignment is: "Rewrite the merge sort algorithm (as described below) as a template function. Use two template parameters, one to set the element type, and the second to define the ordering algorithm."

First off, I thought that the point of a template was so that you can write one 'universal' class/function that could be used for any data type?? So my first question is why would I want to set an element type?

Secondly, why would I (in this case) pass an ordering algorithm into a function that merges??

Thirdly, is it possible to pass an algorithm as a parameter? How would one do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 /**  
   Sorts the elements in a range of a vector.
   @param a the vector with the elements to sort
   @param from start of the range to sort
   @param to end of the range to sort
*/

template <typename T> //implement of template 
void merge_sort(T <int>& a, int from, int to) //Changed vector to typename T
{  
   if (from == to) return;
   int mid = (from + to) / 2;
   // Sort the first and the second half
   merge_sort(a, from, mid);
   merge_sort(a, mid + 1, to);
   merge(a, from, mid, to);
}


I think I have the implementation correct. So I guess I need help with the second and third parts.

Thanks,

David

> Use two template parameters, one to set the element type,
> and the second to define the ordering algorithm.
>> So my first question is why would I want to set an element type?
¿what do you think that template<typename T> means?

>> why would I (in this case) pass an ordering algorithm into a function that merges??
merge takes two ordered list and join them into one ordered list
you need to define an order (i.e. how compare two elements) in order to do that

>> is it possible to pass an algorithm as a parameter? How would one do this?
passing a function, or an object of a class that implements operator()
by instance http://www.cplusplus.com/reference/algorithm/for_each/
Last edited on
Topic archived. No new replies allowed.