c++ - 按数据成员对对象的 vector 进行排序

标签 c++ sorting vector

是的,我知道这是一个重复问题,我已经知道我要找的答案在这里:

Sorting a vector of objects by a property of the object

但是我在将其转换为我自己的代码时遇到了问题。我正在查看上述问题中的代码片段:

struct SortByX
{
    bool operator() const(MyClass const& L, MyClass const& R) {
        return L.x < R.x;
    }
};

std::sort(vec.begin(), vec.end(), SortByX();

我不明白的是 MyClass const & LMyClass const & R 代表什么。而且我没有掌握如何将其应用到我的代码中。

为了提供更多细节,我将 3 种排序方法放入对象 vector 的包装类中,这些对象的参数为 (string, double, , double, bool).总体目标是根据 stringbool 和 3 个 double 中的任何一个对 vector 进行排序。

这是我拥有的最新版本:

void StationVector::sortByGrade(int kindOfGas) {
struct SortByGrade {
    int kindOfGas;

    SortByGrade(int kindOfGas) :
            kindOfGas(kindOfGas) {
    }

    bool operator()(GasStation const &L, GasStation const & R) const {
        return L.getPrice(kindOfGas) < R.getPrice(kindOfGas);
    }
};

std::sort(localStations.begin(), localStations.end(),
        SortByGrade(kindOfGas));
}

SortByGrade(kindOfGas)) 给我以下错误:

没有匹配调用`sort(__gnu_cxx::__normal_iterator >>, __gnu_cxx::__normal_iterator >>, model::StationVector::sortByGrade(int)::SortByGrade)'的函数

最佳答案

SortByX是二元谓词仿函数。二元谓词意味着它接受两个参数并返回一个 bool 值。 Functor 意味着它的实例是可调用的。例如:

MyClass a = ....;
MyClass b = ....;
SortByX comp;
bool flag = comp(a,b); // call this SortByX instance with two MyClass instances

现在,std::sort将在内部使用 SortByX 实例的拷贝您传递它是为了执行 std::vector<MyClass> 的元素之间的比较需要对该 vector 进行排序。

std::vector<MyClass> v;
// fill the vector with MyClass objects
std::sort(v.begin(), v.end(), SortByX()); // sort the vector using a SortByX instance for comparisons

注意:要使其工作,二元谓词必须实现 strict weak ordering .

关于c++ - 按数据成员对对象的 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14803445/

相关文章:

c++ - 当您增加 vector 中结构的大小时会发生什么?

c++ - 如何以 “fun”的方式学习c++?

c++ - 如何使用 boost::bind 将成员函数绑定(bind)到任何对象

c++ - 我需要动态调整对象数组的大小

c++ - 从私有(private) vector 公开访问和赋值运算符

vector - 使用两个自旋向量中的点对球体上的 x、y、z 坐标进行插值?

c++ - 确定我的应用程序何时首次运行

javascript - 如何使用javascript jquery按字母顺序对表格内的默认td进行排序

c# - 使用自定义字母顺序排序

algorithm - 当语言没有这样做的功能时,按字母顺序对项目列表进行排序?