What is the purpose of template <typename T> in this example?

I am reviewing a selection sort algorithm written in C++ and above the functions `template <typename T>` is present. I wonder: What is the purpose of it in this example?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>

using std::cout;
using std::endl;

// Finds the smallest value in an array
template <typename T>
int find_smallest(const std::vector<T>& arr) {
    // stores smallest value
    T smallest = arr[0];
    // stores index of the smallest value
    int smallest_index = 0;

    for (int i = 0; i < arr.size(); i++) {
        if (arr[i] < smallest) {
            smallest = arr[i];
            smallest_index = i;
        }
    }

    return smallest_index;
}

template <typename T>
std::vector<T> selection_sort(std::vector<T> arr) {
    std::vector<T> sorted;

    while(!arr.empty()) {
        // find smallest element and add it to sorted array
        int smallest_index = find_smallest(arr);
        sorted.push_back(arr[smallest_index]);

        // remove smallest element from non-sorted array
        arr.erase(arr.begin() + smallest_index);
    }

    return sorted;
}

int main() {
    std::vector<float> arr = {1.2, 1.0, 3, 0, -1, 0.5, 100, -99};
    std::vector<float> sorted = selection_sort(arr);
    
    cout << "Sorted array: ";
    for (float num : sorted) {
        cout << num << " ";
    }
    cout << endl;
}
This

template <typename T> void ( T );

Declares a template function.

The idea is that the function can be called for any type, whatever T may be, and the compiler will generate a version of the function accepting that type as a parameter, and working on that type within the function (as is typical).

In the case of "find_smallest", it fashions a function that can accept a vector holding any type T, such that all calls to "arr" assume that the vector is holding T's.

Within the function, T smallest will create a variable called "smallest" of type T, as described by the "template parameter".

That receives a copy of a T from "arr[0]", which may not be safe if the vector has no contents (size is zero).

Last edited on
Thanks Niccolo!
Topic archived. No new replies allowed.