使用自定义比较函数进行C 排序

c++ sorting with custom compare function

本文关键字:排序 函数 自定义 比较      更新时间:2023-10-16

我有一个以下类型的向量:

std::vector< std::pair< std::pair< int, int >, std::vector<float> > >  neighbors;

我想创建以下分类以下向量

std::sort( neighbors.begin(), neighbors.end(), myFunc(index) );

在哪里,

bool myFunc( const std::pair< std::pair< int, int >, float > &a, const std::pair< std::pair< int, int >, float > &b, const int index ){
     return ( a.second[index] > b.second[index] );
}

我知道语法是错误的,但我希望提供一个索引以比较向量的元素。

我不确定如何将此参数传递给myfunc。

lambdas:

std::sort(
    neighbors.begin(),
    neighbors.end(),
    [index](const std::pair< std::pair< int, int >, std::vector<float> > &a,  
            const std::pair< std::pair< int, int >, std::vector<float> > &b)
            { 
                 return ( a.second[index] > b.second[index] );
            }
);  

查看C 11中的lambda表达式是什么?用于介绍。

pre-c 11解决方案:使用对象实例作为自定义比较器

struct Comparator {
    Comparator(int index) : index_(index) {}
    bool operator () (const std::pair< std::pair< int, int >, std::vector<float> > &a,
                      const std::pair< std::pair< int, int >, std::vector<float> > &b) 
    {
        return ( a.second[index_] > b.second[index_] );
    }
    int index_;
};
sort(neighbors.begin(), neighbors.end(), Comparator(42));

C 11 解决方案:使用lambda

std::sort(neighbors.begin(), neighbors.end(), [index]
                         (const std::pair< std::pair< int, int >, std::vector<float> > &a, 
                          const std::pair< std::pair< int, int >, std::vector<float> > &b) 
  { 
    return ( a.second[index] > b.second[index] );
  }
);

我的建议:如果允许使用C 11功能,请选择Lambda。它可能更优雅和可读。