Module: Templates in C++


Problem

1/1

Patterns: Start

Theory Click to read/hide

Since the STL is a set of C++ template classes, knowing how these classes are structured is desirable for working with the STL.
C++ has added two new keywords to support templates: "template"; and "typename". Using them, you can write a generic function that will be expanded into the required types at compile time. For example, a template function for obtaining the maximum of two values:

template <typename T>
T myMax(T x, T y)
{
   return (x > y)? x: y;
}
  
int main()
{
  cout << myMax<int >(3,  7) << endl;
  cout << myMax<double >(3.0,  7.0) << endl;
  cout << myMax<char >('g', 'e') << endl;
  
  return 0;
}

 

Problem

Create a template function to implement bubble sort.
 
Examples
# Input Output
1 5
5 4 3 2 1
1 2 3 4 5