C++ 如何使用标准::根据类函数使用比较器

C++ How to use std::sort with comparator based on your class' function

本文关键字:类函数 比较器 何使用 标准 C++      更新时间:2023-10-16

我试图根据函数 calculateDistance() 返回的值对我的向量进行排序,该函数返回双精度值。我想问题是由排列Copmarator方法引起的。.cpp文件如下所示:

bool TSPgenetic::permutationComparator(int* i, int* j){
  return calculateDistance(i) < calculateDistance(j);
}
void TSPgenetic::chooseNewPopulation(){
  sort(population->begin(), population->end(), permutationComparator);
  sort(children->begin(), children->end(), permutationComparator);
`....`
}

头文件片段:

bool permutationComparator(int*, int*);
传递

permutationComparator作为std::sort的第三个参数是无效的。只有static类成员是有效的,并且是函子对象。要解决此问题,这里有四个选择:

  • 使用 lambda 表达式创建一个闭包对象并在那里进行比较。

    std::sort(population->begin(), population->end(), [](const int *i1, const int *i2){return calculateDistance(i1) < calculateDistance(i2);});
    
  • 如果你的
  • 比较函数不需要static,你可以使用 std::bind

    auto comp_func = std::bind(&TSPgenetic::permutationComparator, this, std::placeholders::_1, std::placeholders::_2);
    std::sort(population->begin(), population->end(), comp_func);
    
  • 如果可能的话,将您的比较函数设为static

  • 载类中的bool operator () ( const int *i1, const int *i2 ),以便类成为函子对象。

请注意,从逻辑上讲,比较函数不应是成员函数。它是一个接受两个对象并确定其顺序的函数。因此,几乎所有情况下,只有第三种选择适用。