#ifndef DMCGRATH_FUNC_TEMPLATE_EXAMPLE_HPP #define DMCGRATH_FUNC_TEMPLATE_EXAMPLE_HPP #include namespace dmcgrath{ //generic swap function template void swap_values(T &a, T &b){ T tmp = a; a = b; b = tmp; } /*!************************************************************************* similar to the version in the book, but uses vectors and iterators to make it more useful NB: because we are using a partially specified template type, we need to use the typename keyword. Also, a condition of this working is that the type stored in vector a is less-than-comparable. ***************************************************************************/ template typename std::vector::difference_type index_of_smallest(std::vector a, typename std::vector::difference_type start_index){ //just assume the element at start_index is the smallest T min = a[start_index]; typename std::vector::difference_type index_smallest = start_index; typename std::vector::iterator i; //go from begin() + start + 1 to end() for(i = a.begin() + start_index + 1; i != a.end(); ++i){ //if we are less than min, then we should be min if (*i < min){ min = *i; //get the distance between current iterator location and begin() index_smallest = distance(a.begin(), i); } } return index_smallest; } template void sort(typename std::vector &a){ typename std::vector::difference_type index_smallest; typename std::vector::iterator i; //iterate over the whole vector, swapping as needed for(i = a.begin(); i != a.end(); ++i){ index_smallest = index_of_smallest(a, distance(a.begin(), i)); swap_values(*i, a[index_smallest]); } } } #endif