//srts.cpp --- sort string vector/array, by tsaiwn@csie.nctu.edu.tw #include #include #include #include #include using namespace std; void print(vector c) { vector::iterator i; for(i=c.begin( ); i!= c.end( ); ++i) cout << *i << " "; cout << endl; } // bool comp(const string& a, const string& b) { return b < a; // descending; string in C++ can be compared directly } // 若是 C 的字串 (char array / char* ) 則須用 strcmp(s1, s2) bool comp22(string a, string b) { // call by value for(int i = 0; i x(xa, xa + sizeof(xa)/sizeof(xa[0]) ); // Note! int main( ) { cout << "x: "; print(x); cout << "After sort.." << endl; sort(x.begin(), x.end()); cout << "x: "; print(x); cout << "After sort with sorter comp().." << endl; sort(x.begin(), x.end(), comp); cout << "x: "; print(x); cout << "======\n"; cout << "xa: "; for(int i=0; i< sizeof(xa)/sizeof(xa[0]); ++i) cout << xa[i] << " "; cout << endl; cout << "after sort(xa, xa + number_of_elements)\n"; sort(xa, xa + sizeof(xa)/sizeof(xa[0]) ); // ascending cout << "xa: "; for(int i=0; i< sizeof(xa)/sizeof(xa[0]); ++i) cout << xa[i] << " "; cout << "\nafter Sort xa with comp22 不分大小寫 ...\n"; sort(xa, xa + sizeof(xa)/sizeof(xa[0]), comp22 ); cout << "xa: "; for(int i=0; i< sizeof(xa)/sizeof(xa[0]); ++i) cout << xa[i] << " "; cout << "\n Hit ENTER key..."; cin.get( ); return 0; } /****** Running script C:\testc\handouts\STL>g++ srts.cpp C:\testc\handouts\STL>a.exe x: aaa bbs ABCDE hello Yes chance Good After sort.. x: ABCDE Good Yes aaa bbs chance hello After sort with sorter comp().. x: hello chance bbs aaa Yes Good ABCDE ====== xa: aaa bbs ABCDE hello Yes chance Good after sort(xa, xa + number_of_elements) xa: ABCDE Good Yes aaa bbs chance hello after Sort xa with comp22 不分大小寫 ... xa: aaa ABCDE bbs chance Good hello Yes Hit ENTER key... === === === === === === ******/