#include #include #include "rules.h" using namespace std; void PrintRuleAndArray(const string n[], int size, const string& rule); void sort(string n[], int size); template void sort(string n[], int size, Compare comp); int main() { string names[10] = {"Bob", "Fred", "Ralph", "Joe", "Wanda", "Sam", "Joanna", "billy Joe", "jennifer", "John"}; PrintRuleAndArray(names, 10, "Original name list:"); sort(names, 10); PrintRuleAndArray(names, 10, "Sorted by lexicographic ordering"); sort(names, 10, LengthCompare()); PrintRuleAndArray(names, 10, "Sorted by name length:"); sort(names, 10, AlphabeticCompare()); PrintRuleAndArray(names, 10, "Sorted in alphabetical order:"); sort(names, 10, LastLetterCompare()); PrintRuleAndArray(names, 10, "Sorted by last letter:"); } void PrintRuleAndArray(const string n[], int size, const string& rule) { cout << "---------------------------------\n"; cout << rule << '\n'; for (int i = 0; i < size; i++) cout << n[i] << '\n'; } void sort(string n[], int size) // inefficient old selection sort function // sorts strings on their natural ordering (lexicographic) { int small; for (int i = 0; i < size; i++) { small = i; for (int j = i; j < size; j++) { if (n[j] < n[small]) small = j; } // swap the "small" element on this pass with first slot // of the remaining subarray (n[i]) string temp = n[small]; n[small] = n[i]; n[i] = temp; } } template void sort(string n[], int size, Compare comp) // sorts strings based on the RULE given in the object "comp", which // receives as an argument a function object (i.e. a functor) { int small; for (int i = 0; i < size; i++) { small = i; for (int j = i; j < size; j++) { if ( comp(n[j],n[small]) ) small = j; } // swap the "small" element on this pass with first slot // of the remaining subarray (n[i]) string temp = n[small]; n[small] = n[i]; n[i] = temp; } }