其他分享
首页 > 其他分享> > c – 从结构访问数据时,运算符重载在哪里?

c – 从结构访问数据时,运算符重载在哪里?

作者:互联网

我在一个结构中有一个函数,用于对结构中的向量进行排序.但是为了比较向量中的两个元素,我需要在同一个结构中的另一个变量的值.我想知道我应该在哪里保持运算符重载或比较函数这种工作.我在下面的粘贴中给出了一个样本.

#include<vector>
#include<algorithm>

struct Square{
    int color; //value 1 to 10
};
struct State{
    vector<Square> list;
    int color_weight[] = {4,3,5,2,4,1,6,4,5,9}; //These values keep changing.
    bool operator<(Square& a, Square& b);
    void sortTheList();

};    

bool State::operator<(Square& a, Square& b){
    if (color_weight[a.color]< color_weight[b.color]){
        return true;
    }
    return false;
}

void Square::sortTheList(){
    sort(list.begin(),list.end());
}

当然,这不起作用.我已经尝试了许多其他签名和范围的比较功能,但似乎没有任何工作.

知道在这里可以做些什么吗?

解决方法:

您可以使用比较器来保持对所需额外状态的引用,而不是运算符<.像这样的东西:

struct CompareWeight {
    CompareWeight(int const * weight) : weight(weight) {}
    bool operator()(Square const & lhs, Square const & rhs) {
        return weight[lhs.color] < weight[rhs.color];
    }
    int const * weight;
};

void Square::sortTheList() {
    std::sort(list.begin(), list.end(), CompareWeight(color_weight));
}

标签:stl-algorithm,c,operator-overloading,stl
来源: https://codeday.me/bug/20190826/1731931.html