[英]Sorting vectors of objects by data members
是的,我知道这是一个重复的问题,我已经知道我正在寻找的anwser在这里:
但是我在将其转换为自己的代码时遇到了问题。 我正在从上述问题中查看以下代码段:
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种排序方法放入具有( string
, double
, double
, double
, double
, bool
)参数的对象的包装器类中。 总体目标是按string
, bool
和3个双精度bool
任何一个对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
是二进制谓词函子。 二进制谓词意味着它接受两个参数并返回一个布尔值。 Functor表示它的实例是可调用的。 例如:
MyClass a = ....;
MyClass b = ....;
SortByX comp;
bool flag = comp(a,b); // call this SortByX instance with two MyClass instances
现在, std::sort
将在内部使用传递给它的SortByX
实例的SortByX
,以便在对std::vector<MyClass>
进行排序所需的std::vector<MyClass>
的元素之间进行比较。
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
注意:要使此功能起作用,二进制谓词必须实现严格的弱排序 。
我不明白的是MyClass const&L和MyClass const&R代表什么。
在这种情况下, L
和R
是要比较的容器中的两个项目(类MyClass
实例), L
在小于运算符的左边, R
在右边。 它们通过const-reference传递。
而且我不了解如何将此应用到我的代码中。
在您自己的bool operator() const(MyClass const& L, MyClass const& R)
,您需要比较问题中提到的三个数据成员,尤其要记住应用严格的弱排序 。 如果L
“小于” R
,则返回true
否则返回false
。
正在更新问题...
好像您希望将变量传递到函子中 。 您可以通过创建一个构造函数(例如SSCCE ( 在此处进行编译 ))来做到这一点:
#include <algorithm>
#include <vector>
namespace model {
struct GasStation
{
double getprice(int kindOfGas) const
{
return kindOfGas;
}
};
struct StationVector
{
std::vector<GasStation> localStations;
struct SortByGrade
{
int kindOfGas_;
SortByGrade(int kindOfGas)
:kindOfGas_(kindOfGas)
{
}
bool operator() (GasStation const &L, GasStation const & R) const
{
// You'll need other comparisons here, but this is a good start...
return L.getprice(kindOfGas_) < R.getprice(kindOfGas_);
}
};
void sortByGrade(int kindOfGas)
{
std::sort(localStations.begin(), localStations.end(), SortByGrade(kindOfGas));
}
};
}
int main()
{
model::StationVector sv;
sv.sortByGrade(0);
}
注意: const
限定符位于参数列表之后,而不位于方法名称之后。
另外,请不要将整个方法放在一行上,这会使阅读起来非常困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.