3

構造体のベクトルをソートする関数が構造体にあります。しかし、ベクトル内の2つの要素を比較するには、同じ構造体内の別の変数の値が必要です。この種の機能を実現するには、演算子のオーバーロードまたは比較関数をどこに保持すればよいのか疑問に思いました。次のペーストでサンプルを提供しました。

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

もちろん、これは機能しません。比較関数のために他の多くのシグネチャとスコープを試しましたが、何も機能していないようです。

ここで何ができるか考えてみませんか?

4

1 に答える 1

6

の代わりに、必要な追加の状態への参照を保持するコンパレータを使用しますoperator<。このようなもの:

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));
}
于 2011-12-16T15:56:51.313 に答える