Skip to content

Instantly share code, notes, and snippets.

@jitpaul
Created May 3, 2018
Embed
What would you like to do?
Templates
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <typename T>
void sort(vector<T>& array) {
int i = 0;
while (i < array.size()) {
for (int j = 0; j < array.size() - 1-i; j++) {
if (array[j] > array[j+1]) {
T temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
i++;
}
}
template <>
void sort (vector<string>& array) {
int i = 0;
while (i < array.size()) {
for (int j = 0; j < array.size() - 1 - i; j++) {
if (array[j+1] > array[j]) {
string temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
i++;
}
}
int main() {
// int array
vector<int> intArray = {4,3,6,1};
sort(intArray);
for (int each : intArray) cout << each << " ";
cout << endl;
// char array
vector<char> charArray = {'b','r','w','p'};
sort(charArray);
for (char each : charArray) cout << each << " ";
cout << endl;
//string array
vector<string> stringArray = { "hello","how","are","you" };
sort(stringArray);
for (string each : stringArray) cout << each << " ";
cout << endl;
cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment