2013-02-24 194 views
0

通常在C++中使用兩個參數比較的sort功能,例如:傳遞第三個參數進行排序的C函數++(STL)

sort(v.begin(),v.end(),compare); 

bool compare(int a,int b) 
. 
. 
. 

但在矢量我已存儲陣列,我想sort矢量基於特定的索引。即:

int arr[3]; 

vector<arr> v; 

如何使用排序功能,如果我想基於索引0或1或2(取決於用戶的輸入)排序V'這裏的問題是,當我會寫的比較功能:

bool compare(int *arr,int *arr1) 

話,我怎麼能知道這個功能進行排序特定指數的基礎上?

+0

不能存儲C-陣列標準集裝箱...你能告訴我們你的真正的代碼? – 2013-02-24 19:27:33

+0

你是什麼意思'排序v基於索引0或1或2'? – 2013-02-24 19:29:13

+0

struct coord \t { \t \t int * arr; \t}; \t vector v; 這裏我想根據arr的索引對v進行排序,即有時我想使用arr [0]或arr [1]或arr [2]對所有類型爲coord的對象進行排序。 – SIGSTP 2013-02-24 19:29:55

回答

5

只需使用仿函數對象:

struct coord { int *arr; }; 
struct Comparer : std::binary_function<coord,coord,bool> { 
    Comparer(int base) : m_base(base) {} 
    bool operator()(const coord &c1, const coord &c1) 
    { 
     return c1.arr[m_base] < c2.arr[m_base]; 
    } 
private: 
    int m_base; 
}; 
//... 
std::sort(v.begin(), v.end(), Comparer(1)); 
+0

在C++ 11中,這更符合lambda表達式。 – Yakk 2013-02-24 20:07:53

+0

您的Comparer類應該擴展std :: binary_function。 – 2013-02-24 20:37:00

+0

@Alex是的,謝謝,更新 – Slava 2013-02-24 20:43:25