0

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

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)

那么我怎样才能告诉这个函数根据特定索引进行排序呢?

4

1 回答 1

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 ) );
于 2013-02-24T19:27:02.067 回答