【问题标题】:Passing a third argument to sort function of C++(STL)将第三个参数传递给 C++(STL) 的排序函数
【发布时间】:2013-02-24 19:24:14
【问题描述】:

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

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)

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

【问题讨论】:

  • 您不能将 C 数组存储在标准容器中...您能向我们展示您的真实代码吗?
  • sort v based on index 0 or 1 or 2 是什么意思?
  • 结构坐标 { int *arr; };矢量 v;在这里,我想根据 arr 的索引对 v 进行排序,即有时我想使用 arr[0] 或 arr[1] 或 arr[2] 对所有 coord 类型的对象进行排序。
  • 我根据你的坐标结构调整了我的例子。但这并不重要,我想你会明白的。

标签: c++ stl


【解决方案1】:

只需使用仿函数对象:

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 ) );

【讨论】:

  • 在 c++11 中,使用 lambdas 更加简洁。
  • 您的 Comparer 类应该扩展 std::binary_function。
猜你喜欢
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多