How to have a set of structs in C++
May 31, 2021
One
struct Foo
{
int key;
};
inline bool operator<(const Foo& lhs, const Foo& rhs)
{
return lhs.key < rhs.key;
}
Two
struct Foo
{
int key;
};bool compareFoo(const Foo &lhs, const Foo &rhs)
{
return lhs.x < rhs.x;
}
std::set<Foo,compareFoo> mySet;
Three
struct Foo
{
int key;
bool operator < (const Foo &other) const
{
return key < other.key;
}
};
Four (lambda expression)
struct Foo
{
int key;
};auto compareFoo = [](Foo lhs, Foo rhs) { return lhs.x < rhs.x;};
set<Foo, decltype(compareFoo)> mySet(compareFoo);
Reference
[1] https://stackoverflow.com/questions/5816658/how-to-have-a-set-of-structs-in-c