是的,我知道这是一个重复问题,我已经知道我要找的答案在这里:
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 & L
和 MyClass const & R
代表什么。而且我没有掌握如何将其应用到我的代码中。
为了提供更多细节,我将 3 种排序方法放入对象 vector 的包装类中,这些对象的参数为 (string
, double
, 双
, double
, bool
).总体目标是根据 string
、bool
和 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/