  1 //sortVec.cpp  --- demo using sort in <algorithm> to sort a vector
  2 // @CopyLeft by tsaiwn@csie.nctu.edu.tw
  3 #include <iostream>
  4 #include <vector>
  5 #include <algorithm>
  6 #include <string>
  7 #include <string.h>
  8 #include <cctype>
  9 using namespace std;
 10 
 11 // function to do comparison, not case sensitive.
 12 bool compare_nocase (string first, string second) {
 13   unsigned int i=0;
 14   while ( (i<first.length()) && (i<second.length()) )
 15   {
 16     if (tolower(first[i])<tolower(second[i])) return true;
 17     else if (tolower(first[i])>tolower(second[i])) return false;
 18     ++i;
 19   }
 20   if (first.length()<second.length()) return true;
 21   else return false;
 22 }
 23 /***/
 24 bool mycomp(string x, string y) {  cout << " haha ";
 25    return strcmp(y.c_str( ), x.c_str( ) ) < 0;
 26 }
 27 /***/
 28 void printVector(vector<string> x) {
 29  for(int i=0; i< x.size( ); ++i)  cout << " " << x[i];
 30  cout << endl;
 31 }
 32 ///////////////////
 33 int main ( ) {
 34   vector<string> xx;
 35   xx.push_back("aaa"); xx.push_back("ccc");  xx.push_back("bbb");
 36   xx.push_back("BBS"); xx.push_back("egg"); xx.push_back("EGG_BIG");
 37   cout << "vector xx: ";  printVector(xx);
 38 
 39   sort(xx.begin( ), xx.end( ) );    // ascending 
 40   cout << "\n=== after sort\n  vector xx: ";   printVector(xx);
 41 
 42   cout << "\n=== now calling sort with mycomp.. ";
 43   sort(xx.begin( ), xx.end( ) , mycomp);    
 44   cout << "\n=== after sort(..., mycomp)\n  vector xx: ";
 45   printVector(xx);
 46 
 47   sort(xx.begin( ), xx.end( ) , compare_nocase);    
 48   cout << "\n=== after sort(..., compare_nocase)\n  vector xx: ";
 49   printVector(xx);
 50   return 0;
 51 } // main(
 52 /******
 53 C:\testc>g++ sortVec.cpp
 54 
 55 C:\testc>a.exe
 56 vector xx:  aaa ccc bbb BBS egg EGG_BIG
 57 
 58 === after sort
 59   vector xx:  BBS EGG_BIG aaa bbb ccc egg
 60 
 61 === now calling sort with mycomp..  haha  haha  haha  haha  haha
 62 === after sort(..., mycomp)
 63   vector xx:  egg ccc bbb aaa EGG_BIG BBS
 64 
 65 === after sort(..., compare_nocase)
 66   vector xx:  aaa bbb BBS ccc egg EGG_BIG
 67 
 68 C:\testc>                   *******************************/
