結構體和類的排序問題

來源:互聯網
上載者:User
寫第一篇文章,就被csdn的blog搞得無語了,居然插入代碼裡面沒有C++,BS!
 
好吧,開始本文:
簡單的string、int、char經常都不能滿足我們這些貪婪的程式員,所以我們不得不藉助struct或者class
來描述事物,當struct或class多起來的時候,我們就得想到數組和鏈表;鏈表的話,指標指來指去,最常
被忽悠的是我們自己,普通的數組又無法滿足我們的struct和class;所以我們今天討論的是vector;
  可是對struct和class的排序怎麼辦?自己寫排序,稍不留神,就會讓程式留下bug而不自知;
  所以本文討論的是vector的排序,看代碼吧:
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
using namespace std;
class student{
public:
 student(const string &a, int b):name(a), score(b){}
 string name;
 int score;
 bool operator < (const student &m)const {
  return score< m.score;
 }
};
int main() {
 vector< student> vect;
 student st1("Tom", 74);
 vect.push_back(st1);
 st1.name="Jimy";
 st1.score=56;
 vect.push_back(st1);
 st1.name="Mary";
 st1.score=92;
 vect.push_back(st1);
 st1.name="Jessy";
 st1.score=85;
 vect.push_back(st1);
 st1.name="Jone";
 st1.score=56;
 vect.push_back(st1);
 st1.name="Bush";
 st1.score=52;
 vect.push_back(st1);
 st1.name="Winter";
 st1.score=77;
 vect.push_back(st1);
 st1.name="Andyer";
 st1.score=63;
 vect.push_back(st1);
 st1.name="Lily";
 st1.score=76;
 vect.push_back(st1);
 st1.name="Maryia";
 st1.score=89;
 vect.push_back(st1);
 cout<<"------before sort..."<<endl;
 for(int i = 0 ; i < vect.size(); i ++) cout<<vect[i].name<<":/t"<<vect[i].score<<endl;
 stable_sort(vect.begin(), vect.end(),less<student>());
 cout <<"-----after sort ...."<<endl;
 for(int i = 0 ; i < vect.size(); i ++) cout<<vect[i].name<<":/t"<<vect[i].score<<endl;
 return 0 ;
}
呵呵,相信看完這段代碼,應該就能使用sort對vector的排序了;
再補充點東西,就更完美了
 
 
函數名  功能描述  
sort  對給定區間所有元素進行排序 
stable_sort  對給定區間所有元素進行穩定排序 
partial_sort  對給定區間所有元素部分排序 
partial_sort_copy  對給定區間複製並排序 
nth_element  找出給定區間的某個位置對應的元素 
is_sorted  判斷一個區間是否已經排好序 
partition  使得符合某個條件的元素放在前面 
 
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.