Reputation: 74
I try to create a custom class used with std::set
. I know I need to provide a custom comparator for it so I overloaded the operator<
. But when I try to copy the set with the code set<Edge> a; set<Edge> b = a;
,
I get the following error:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__functional_base:63:21: Invalid operands to binary expression ('const Edge' and 'const Edge')
class Edge {
public:
Edge(int V, int W, double Weight):v(V),w(W),weight(Weight){}
int other(int vertex){ return v ? w : vertex == w;}
int v,w;
double weight;
friend std::ostream& operator<<(std::ostream& out, const Edge& e)
{
out<<e.v<<' '<<e.w<<' '<<"weight:"<<e.weight<<'\n';
return out;
}
bool operator<(const Edge& other)
{
return weight < other.weight;
}
};
Upvotes: 1
Views: 388
Reputation: 56557
Make
bool operator<(const Edge& other) const
as the comparison operator must be marked const
. The keys in a std::set
are const
, so the operator<
is invoked on a const
instance, hence must be marked const
.
Upvotes: 5