2013-02-24 198 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