How to have a set of structs in C++

--

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

--

--

No responses yet