-
-
Save jitpaul/b5e249d9a8e93e03f1607397b32fb70b to your computer and use it in GitHub Desktop.
Templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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