構造体のベクトルをソートする関数が構造体にあります。しかし、ベクトル内の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());
}
もちろん、これは機能しません。比較関数のために他の多くのシグネチャとスコープを試しましたが、何も機能していないようです。
ここで何ができるか考えてみませんか?