Reputation: 45
I am trying to use remove method from list on struct object to remove it. This is my struct:
typedef struct pair{
int x;
int y;
} PAIR;
And this is code where i use it and where the error occurs:
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);
Error that i am getting is this:
no match for ‘operator==’ (operand types are ‘pair’ and ‘const value_type’ {aka ‘const pair’})
Can you tell me how to fix this?
Upvotes: 0
Views: 80
Reputation: 595582
To use std::list::remove()
, elements have to be comparable for equality. Implement an operator==
for your struct, eg:
typedef struct pair{
int x;
int y;
bool operator==(const pair &rhs) const {
return x == rhs.x && y == rhs.y;
}
} PAIR;
Otherwise, use std::find_if()
and 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);
}
Or, std::list::remove_if()
:
openSet.remove_if(
[&](const PAIR &p){ return p.x == current.x && p.y == current.y; }
);
Or, change your loop to use iterators explicitly:
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);
}
Upvotes: 5