使用STL库sort函数对vector进行排序,vector的内容为对象的指针,而不是对象。
代码如下
1 #include <stdio.h> 2 #include <vector> 3 #include <algorithm> 4 5 using namespace std; 6 7 class Elm 8 { 9 public: 10 int m_iSortProof; 11 12 private: 13 int __m_iValue; 14 static int __m_iCnt; 15 16 public: 17 Elm(); 18 int getValue(int iX); 19 void printElm(); 20 }; 21 22 int Elm::__m_iCnt = 0; 23 24 Elm::Elm() 25 { 26 __m_iCnt ++; 27 __m_iValue = __m_iCnt; 28 m_iSortProof = getValue(__m_iCnt); 29 } 30 31 /* (x-10.3)^2 + 0.6*/ 32 int Elm::getValue(int iX) 33 { 34 float fX = (float)iX - 10.3; 35 36 float fY = fX * fX + 0.6; 37 38 return (int)fY; 39 } 40 41 void Elm::printElm() 42 { 43 printf("value : %3d, proof : %3d ", __m_iValue, m_iSortProof); 44 } 45 46 /*z -> a*/ 47 bool compare(const Elm * a, const Elm * b) 48 { 49 return a->m_iSortProof > b->m_iSortProof; 50 } 51 52 int main(int argc, char * argv[]) 53 { 54 vector<Elm *> vecpList; 55 int i = 0; 56 for(i = 0; i < 20; i++) 57 { 58 Elm * pElm = new Elm; 59 vecpList.push_back(pElm); 60 } 61 for(vector<Elm *>::iterator pE = vecpList.begin(); pE != vecpList.end(); pE++) 62 { 63 (*pE)->printElm(); 64 } 65 /*使用sort对vector进行排序*/ 66 sort(vecpList.begin(), vecpList.end(), compare); 67 printf("