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

Sorting vectors of objects by data members

本文关键字:排序 数据成员 对象      更新时间:2023-10-16

是的,我知道这是一个重复的问题,我已经知道我要找的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 & LMyClass const & R所代表的是什么。我不知道如何将其应用到我的代码中。

为了提供更详细的信息,我将把3个排序方法放入对象向量的包装类中,这些对象向量的参数为(stringdoubledoubledoublebool)。总体目标是根据stringbool和3个双打中的任何一个对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_xx::__normal_iterator>>,model::StationVector::sortByGrade(int)::SortByGrad)"时没有匹配的函数

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

注意:为了实现这一点,二进制谓词必须实现严格的弱排序。

我不明白的是MyClass const&L、 和MyClass常量&R.

在本例中,LR是正在比较的容器中的两个项(类MyClass的实例),L在小于运算符的左侧,R在右侧。它们是通过常量引用传入的。

我不知道如何将其应用到我的代码中。

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

另外,请不要把整个方法放在一行上,这会让它很难阅读。