按数据成员对对象的矢量进行排序

时间:2013-02-10 22:40:01

标签: c++ sorting vector

是的,我知道这是一个重复的问题,我已经知道我正在寻找的anwser在这里:

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种排序方法放入参数为(stringdoubledouble,{{1}的对象向量的包装类中},double)。最重要的目标是按boolvector以及3个双打中的任何一个对string进行排序。

这是我的最新版本:

bool

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)); } 行给出了以下错误:

没有匹配函数来调用`sort(__ gnu_cxx :: __ normal_iterator&gt;&gt;,__ gn_cxx :: __ normal_iterator&gt;&gt;,model :: StationVector :: sortByGrade(int):: SortByGrade)'

2 个答案:

答案 0 :(得分:2)

SortByX是二元谓词仿函数。二进制谓词意味着它需要两个参数并返回一个布尔值。 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>元素之间的比较。

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

答案 1 :(得分:1)

  

我不明白的是MyClass const&amp; amp; L和MyClass const&amp; R上。

LR,在这种情况下是来自容器的两个项目(MyClass的实例),正在进行比较,左侧是L小于运算符和右侧R。它们通过const-reference传入。

  

我并不了解如何将其应用于我的代码。

在您自己的bool operator() const(MyClass const& L, MyClass const& R)中,您需要比较您在问题中提到的三个数据成员,记住要应用strict weak ordering。如果true“小于”L,则返回R,否则返回false


对问题进行更新后......

您希望将变量传递到functor。您可以通过创建构造函数来完成此操作,例如SSCCEcompiles here):

#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限定符位于参数列表之后,而不是在方法名称之后。

另外,请不要将整个方法放在一行,这使得阅读非常困难。

相关问题