使用C++中的remove方法从列表中删除Struct对象



我正在尝试使用remove方法从结构对象的列表中删除它。这是我的结构:

typedef struct pair{
int x;
int y;
} PAIR;

这是我使用它的地方和错误发生的地方的代码:

list<PAIR> openSet;
PAIR pair;
pair.x = xStart;
pair.y = yStart;
openSet.push_front(pair);
PAIR current;
for(PAIR p : openSet){
if(fScores[p.x * dim + p.y] < maxVal){
maxVal = fScores[p.x * dim + p.y];
current = p;
}
}
openSet.remove(current);

我得到的错误是:

no match for ‘operator==’ (operand types are ‘pair’ and ‘const value_type’ {aka ‘const pair’})

你能告诉我怎么修吗?

要使用std::list::remove(),元素必须具有相等性。为您的结构实现operator==,例如:

typedef struct pair{
int x;
int y;
bool operator==(const pair &rhs) const {
return x == rhs.x && y == rhs.y;
}
} PAIR;

否则,使用std::find_if()std::list::erase():

auto iter = std::find_if(openSet.begin(), openSet.end(),
[&](const PAIR &p){ return p.x == current.x && p.y == current.y; }
);
if (iter != openSet.end()) {
openSet.erase(iter);
}

或者,std::list::remove_if():

openSet.remove_if(
[&](const PAIR &p){ return p.x == current.x && p.y == current.y; }
);

或者,将循环更改为显式使用迭代器:

list<PAIR>::iterator current = openSet.end();
for(auto iter = openSet.begin(); iter != openSet.end(); ++iter){
PAIR &p = *iter;
if (fScores[p.x * dim + p.y] < maxVal){
maxVal = fScores[p.x * dim + p.y];
current = iter;
}
}
if (current != openSet.end()) {
openSet.erase(current);
}

最新更新