问题
I am working on an A* pathfinding algorithm, but am having trouble with an error I receive when i insert a struct called node into a set. The error reads: "Error 1 error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const node' (or there is no acceptable conversion)" but the error is found in another file 'XSTDDEF' which i haven't looked at. I am unsure of what it means.
struct node{
int f;
int g;
int h;
int x;
int y;
};
node coords[24] = { -1 };
std::set<node> open;
std::set<node> closed;
int main(int argc, char *argv[]){
coords[4].g = 0;
coords[4].h = heuristic(start, end, start.h);
coords[4].f = start.g + start.h;
coords[4].x = 4;
coords[4].y = 0;
open.insert(coords[4]);
回答1:
As you may know if you've familiarized yourself with the documentation of std::set
, it is an ordered container. Therefore there must be a way to compare the elements of the set so that they can be ordered. From the documentation, we know that the default comparison functor of std::set
is std::less<T>
.
Further, as you may know, std::less<T>
does:
Unless specialized, invokes operator< on type T.
Since std::less
isn't specialized for node
, it uses operator<
.
The error message tells you that an overload for operator<
does not exist that would have const node
(or anything that a node
could be converted to) as the left operand.
The solution is to define such overload.
回答2:
std::set is an ordered container so it needs operator< to compare and order elements, allowing fast search. If you don't need this you can use list or vector.
回答3:
You need to create operator<
or specialize std::less
for your struct. Another solution could be to use std::array
:
struct node : std::array<5,int> {
int &f() { return data()[0]; }
int &g() { return data()[1]; }
int &h() { return data()[2]; }
int &x() { return data()[3]; }
int &y() { return data()[4]; }
};
and you will inherit operator<
from it. Another benefit - you can access underlying data as array, which would simplify serializing etc.
来源:https://stackoverflow.com/questions/40914705/trouble-inserting-a-struct-into-a-set-c