//sortVec3.cpp --- sorting vector again, with Comparator //@CopyLeft by tsaiwn@csie.nctu.edu.tw #include #include #include using namespace std; bool compare (int i,int j) { cout << " ha "; return (ij); } //Descending // the following defines a Comparator class "Sorter" typedef class { public: // struct default public: but class def private bool operator( ) (int i,int j) { cout << " S "; return (i void printV(vector aVt) { typename vector::iterator it; // used to print out content cout << "\n Vector contains:"; for (it=aVt.begin(); it!=aVt.end(); ++it) cout << " " << *it; cout<< "\n front, back == "<< aVt.front( )<<", "<< aVt.back( )< myvector(myints, myints+(sizeof myints/sizeof myints[0])); printV(myvector); //sort(myvector.begin( ), myvector.end( )); // use operator< sort(myvector.begin( ), myvector.begin( )+4); // sort only first 4 items //(12 32 45 71)26 80 53 33 printV(myvector); // using compare function to sort // 12 32 45 71(26 33 53 80) sort(myvector.begin()+4, myvector.end(), compare); printV(myvector); // using an Object as comparator //(12 26 32 33 45 53 71 80) sort(myvector.begin(), myvector.end(), myObject); printV(myvector); cout << "Now sort all data with function comp222( ) ..."; sort(myvector.begin( ), myvector.end( ), comp222); printV(myvector); double y[ ]={3.8, 4.9, 2.5, 40, 55}; vector vd(y, y+3); // 3 elements cout << " vector vd: "; printV(vd); return 0; }//main( /****** C:\testc\STL>g++ sortVec3.cpp C:\testc\STL>a Vector contains: 32 71 12 45 26 80 53 33 front, back == 32, 33 Vector contains: 12 32 45 71 26 80 53 33 front, back == 12, 33 ha ha ha ha ha ha ha ha ha Vector contains: 12 32 45 71 26 33 53 80 front, back == 12, 80 S S S S S S S S S S S S S S S S S S S S Vector contains: 12 26 32 33 45 53 71 80 front, back == 12, 80 Now sort all data with function comp222( ) ... C C C C C C C Vector contains: 80 71 53 45 33 32 26 12 front, back == 80, 12 vector vd: Vector contains: 3.8 4.9 2.5 front, back == 3.8, 2.5 **********************/