Sorting a Generics Array in C++ ( The easy way) .

Let's first have an idea about what is Generics .

A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.

In C++ Generics are implemented using template .

Generics can be useful for classes like LinkedList, binary tree, Stack, Queue, Array, etc.

Here is a simple Array Sorting Program using Generics in C++ ::

#include "iostream"
#include "typeinfo"
#include "sstream"
#include "iterator"

using namespace std;

template <typename T>
T * Sort(T arr[] , int n){ // we used bubble sort for making it simple 

    for (int i = 0; i < n-1; i++){
        for (int j = 0; j < n-i-1; j++){
             if (arr[j] > arr[j+1]){  
                  T temp = arr[j];
                  arr[j] = arr[j+1];
                  arr[j+1] = temp;
             };

         }
    };
    return arr;
};

unsigned int countWordsInString(std::string const& str)
{
    std::stringstream stream(str);
    return std::distance(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>());
};

int main(){

    string line = "The Fox Jumped Over the Hill ";
    size_t length = countWordsInString(line);

    string arr[length];
    int i = 0;

    stringstream ssin(line);

    while (ssin.good() && i < line.length()){
        ssin >> arr[i];
        ++i;
    }

    int n = sizeof(arr) / sizeof(arr[0]);

    string * sorted_arr =  Sort(arr,  n);

    for (int i = 0; i <= n - 1; i++)
    {
        cout << sorted_arr[i] << endl;
    };

    // By changing above array datatype sorting can be performed on String , numerics and chars .

    return 0;
};

Output for the above program ::

Fox
Hill
Jumped
Over
The
the