Saturday, January 25, 2020

Introduction to Template and Function Pointer in C++



#include <iostream>

using namespace std;

template<typename T>
bool ascending(T a, T b) {
    return a > b;
}

template<typename T>
bool descending(T a, T b) {
    return a < b;
}

template<typename T>
void sort(T *p, int size, bool (*f)(T a, T b)) {
    for (int i = 0; i < size; i++) {
        for(int j = i; j < size; j++) {
            if (f(p[i], p[j])) {
                swap(p[i], p[j]);
            }
        }
    }
}

template<typename T>
void swap(T *a, T *b) {
    T temp = *a;
    *a = *b;
    *b = temp;
}

template<typename T>
void print(T* q, int size) {
    for(int i = 0; i < size; i++) {
        cout<<q[i]<<" ";
    }
    cout<<endl;
}

void expSwap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main()
{
    int i = 10, j = 20;
    expSwap(&i, &j);
    cout<<i<<" "<<j<<endl;
    int a = 0, b = 1;
    swap(a, b);
    cout<<a<<" "<<b<<endl;
    double c = 1.05, d = 2.05;
    swap(c, d);
    cout<<c<<" "<<d<<endl;
    int A[] = {5, 1, 2, 3, 4};
    print(A, 5);
    sort(A, 5, ascending);
    print(A, 5);
    sort(A, 5, descending);
    print(A, 5);
    char C[] = {'e', 'a', 'b', 'c', 'd'};
    print(C, 5);
    sort(C, 5, ascending);
    print(C, 5);
    sort(C, 5, descending);
    print(C, 5);
    double D[] = {5.05, 1.01, 2.02, 3.03, 4.04};
    print(D, 5);
    sort(D, 5, ascending);
    print(D, 5);
    sort(D, 5, descending);
    print(D, 5);
    return 0;
}