SparrowG
SparrowG

Reputation: 221

Where does the operator overloading go when accessing data from a struct?

I have a function in a struct that sorts a vector in the struct. But to compare two elements in the vector, I need value of another variable inside the same struct. I was wondering where I should keep the operator overload or the compare function for this sort to work. I've given a sample in the following paste.

#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());
}

This doesn't work, of course. I've tried many other signatures and scope for the comparison function but nothing seems to work.

Any idea what can be done here?

Upvotes: 3

Views: 182

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254621

You would use a comparator that keeps a reference to the extra state that it needs, instead of operator<. Something like this:

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));
}

Upvotes: 6

Related Questions