//sortSTL.cpp -- Demo using sort( ) in C++ STL Library // @CopyLeft by tsaiwn@cs.nctu.edu.tw; 這個程式是 C++ 程式, 必須用 g++ // 站在巨人肩膀上: 使用女共匪寫的 C++ STL 程式庫的 sort( ) #include #include using namespace std; // 規定要這樣才可用 C++ 程式庫 std:: int x[ ] = {38, 49, 88, 58, 38, 77, 66, 68, 55, 95, 88, 65}; const int NX = (sizeof x / sizeof x[0]); double y[ ]={55, 68.5, 66.6, 78.5, 38, 49, 38, 88, 58}; const int NY = (sizeof y / sizeof y[0]); template void print(T a, int n) { int i; cout << " "<< a[0]; // cout 就是螢幕 for(i=1; i < n; i++) { if(i%5 == 0) cout << endl<< " "< // 注意這是樣板函數(template function) bool comp(const GG& a, const GG& b) { return b < a; } //遞減 int main( ) { char ggtmp[99]; cout << "Before sort:\n"; print(x, NX); sort(x, x+NX); // 由小到大, 自然序 cout << " After sort:\n"; print(x, NX); cout << " Sort again with compare function comp:\n"; sort(x, x+NX, comp); print(x, NX); cout << "=== === ===\n"; cout << "Before sort y:\n"; print(y, NY); sort(y, y+NY); // 由小到大 cout << " After sort:\n"; print(y, NY); cout << " Sort again with compare function comp():\n"; sort(y, y+NY, comp); print(y, NY); cout << "Hit any key and then ENTER key..."; cin >> ggtmp; //暫停! cin 就是鍵盤, 注意要打至少一字後按 ENTER return 0; }// main( /****** 注意 compare function 是 bool 要回傳 true 或 false D:\test> path C:\Dev-Cpp\bin;%path% D:\test> g++ sortSTL.cpp D:\test> a.exe Before sort: 38, 49, 88, 58, 38 77, 66, 68, 55, 95 88, 65 After sort: 38, 38, 49, 55, 58 65, 66, 68, 77, 88 88, 95 Sort again with compare function comp: 95, 88, 88, 77, 68 66, 65, 58, 55, 49 38, 38 === === === Before sort y: 55, 68.5, 66.6, 78.5, 38 49, 38, 88, 58 After sort: 38, 38, 49, 55, 58 66.6, 68.5, 78.5, 88 Sort again with compare function comp(): 88, 78.5, 68.5, 66.6, 58 55, 49, 38, 38 Hit any key and then ENTER key...bye D:\test> *** === 看完這有沒有發現 C++ 寫這麼短的程式就能做這麼多事? ******/