vector用sort演算法排序

2021-07-11 10:46:02 字數 915 閱讀 8130

用sort對vector排序有兩種方法

方法1:

#include //容器的標頭檔案

#include //sort演算法用到的標頭檔案

#include //greater模版函式用到的標頭檔案

using namespace std;

struct info

; bool info::operator >(const info& pinfo) const

bool info::operator<(const info& pinfo) const

int main(int argc, char* argv)

sort(m_vecinfo.begin(),m_vecinfo.end(),greater());//降序排列

sort(m_vecinfo.begin(),m_vecinfo.end(),less()); //公升序排列

return 0;

}方法2:

using namespace std;

struct info ;

bool copare(const info* pfirst,const info* psecond) //如果該vector存入的是物件的話該函式引數須是

int main(int argc, char* argv)

sort(m_vecinfo.begin(),m_vecinfo.end(),copare); //按照自己寫的排序函式進行排序

return 0;

} 總結:這兩個方法都可實現vector的排序,當vector存入的是物件時兩種方法都行(只要把第二種方法的用於排序的分成員函式的引數列表寫成物件的引用即可),但是當vector裡是指標的時候只能用第二種方法進行排序。

應該還有別的方法,但是我沒有測試過,因此只介紹這兩種方法。

Vector的自動排序Sort

建立了乙個結構體,然後用容器進行存放,想對其進行排序。vector支援sort函式,但是需要自己指定排序函式。方法如下 1.需要包含標頭檔案 include include using namespace std 2.宣告結構體 typedef struct mydata mydata 3.定義比較...

sort按vector元素排序

include include include using namespace std typedef struct example example 這個comparison函式很重要.如果希望公升序排序,就是 降序排列就是 號 這樣便於直觀記憶.如果希望用elem2作為比較標準 就把elem1改為...

vector 排序方法sort的使用

使用vector的sort方法,有兩種形式,一種是在類內部使用操作符過載實現,一種是在類外面寫乙個比較函式。但是sort方法無法直接傳入其它形參,在需要動態排序相對某個人的位置時,採取了間接通過靜態變數的方法。為防止併發量巨大時,靜態變數無法及時改變而產生錯誤資料,故用一迴圈去驗證等待賦值,排完序後...