C++ Code Example 5: Advanced Function Template Example

In this example, the “quicksort” function template takes a reference to a vector of elements of any type “T”, and two integer arguments “left” and “right” that represent the left and right boundaries of the vector that needs to be sorted. The quicksort algorithm recursively partitions the vector around a pivot element and sorts the partitions.

The main function demonstrates how the “quicksort” function template can be used with vectors of different types of data. It creates two vectors, “vec1” of integers and “vec2” of doubles. The “quicksort” function is called twice, once with each vector, to sort the elements. The output displays the sorted vectors.

Note that the type parameter “T” is inferred from the data type of the vector elements. This allows the “quicksort” function template to work with vectors of any type of data that supports the less than operator (“<“).

Function templates can be very powerful and useful when working with generic algorithms, data structures, and containers that can work with different types of data. The quicksort example demonstrates how a function template can be used to sort vectors of any type of elements using a single function template.

#include &lt;iostream&gt;
#include &lt;vector&gt;

template &lt;typename T&gt;
void quicksort(std::vector<T>& vec, int left, int right) {
    if (left < right) {
        int i = left;
        int j = right;
        T pivot = vec[(left + right) / 2];
        while (i <= j) {
            while (vec[i] < pivot) {
                i++;
            }
            while (vec[j] > pivot) {
                j--;
            }
            if (i <= j) {
                std::swap(vec[i], vec[j]);
                i++;
                j--;
            }
        }
        quicksort(vec, left, j);
        quicksort(vec, i, right);
    }
}

int main() {
    std::vector&lt;int&gt; vec1 {3, 5, 1, 4, 2};
    quicksort(vec1, 0, vec1.size() - 1);
    std::cout << "Sorted vector 1: ";
    for (int v : vec1) {
        std::cout << v << " ";
    }
    std::cout << std::endl;

    std::vector&lt;double&gt; vec2 {2.2, 1.1, 3.3, 5.5, 4.4};
    quicksort(vec2, 0, vec2.size() - 1);
    std::cout << "Sorted vector 2: ";
    for (double v : vec2) {
        std::cout << v << " ";
    }
    std::cout << std::endl;

    return 0;
}