传递第三个参数来对C++(STL)的函数进行排序

SIG*_*STP 0 c++ stl

通常比较sortc ++中的函数需要两个参数,例如:

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

bool compare(int a,int b)
.
.
.
Run Code Online (Sandbox Code Playgroud)

但是在向量中我存储了一个数组,我想要sort基于特定索引的向量.即:

int arr[3];

vector<arr> v;
Run Code Online (Sandbox Code Playgroud)

如果我想根据索引0或1或2(取决于用户的输入)对v进行排序,我该如何使用sort函数?这里的问题是,当我写比较函数时:

bool compare(int *arr,int *arr1)
Run Code Online (Sandbox Code Playgroud)

那我怎么能告诉这个函数在特定索引的基础上排序呢?

Sla*_*ica 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 ) );
Run Code Online (Sandbox Code Playgroud)