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

问题描述

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

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