I would like to create a set containing the objects of my class, I have to determine a custom comparison. Unfortunately, everything I tried did not work.
class My_Class {
public:
char letter;
set<My_Class, compare> Children;
};
Ant then, the compare struct:
struct compare {
bool operator() (const My_Class& a, const My_Class& b) const{
return a.letter < b.letter;
}
};
How can I make this work please?
Currently, the issue displays that identifiers a
and b
are not declared.
You are trying to use compare
structure inside My_Class
, which uses My_Class
in its method. It is not a trivial case, but forward declaration will help. So this should work:
class My_Class;
struct compare {
bool operator() (const My_Class &a, const My_Class &b) const;
};
class My_Class {
public:
char letter;
set<My_Class, compare> Children;
};
bool compare::operator() (const My_Class &a, const My_Class &b) const
{
return a.letter < b.letter;
}
Another alternative would be to pass comparator to std::set constructor, rather than specify it as a template parameter:
class My_Class {
public:
My_Class();
char letter;
set<My_Class> Children;
};
struct compare {
bool operator() (const My_Class& a, const My_Class& b) const{
return a.letter < b.letter;
}
};
My_Class::My_Class() : Children( compare() )
{
}