Spa*_*owG 3 c++ stl operator-overloading stl-algorithm
我在一个结构中有一个函数,用于对结构中的向量进行排序.但是为了比较向量中的两个元素,我需要在同一个结构中的另一个变量的值.我想知道我应该在哪里保持运算符重载或比较函数这种工作.我在下面的粘贴中给出了一个样本.
#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());
}
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用.我已经尝试了许多其他签名和范围的比较功能,但似乎没有任何工作.
知道在这里可以做些什么吗?
您将使用比较器来保持对所需的额外状态的引用,而不是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));
}
Run Code Online (Sandbox Code Playgroud)