微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。