How to have a set of structs in C++

This might help:

struct foo
{
  int key;
};

inline bool operator<(const foo& lhs, const foo& rhs)
{
  return lhs.key < rhs.key;
}

If you are using namespaces, it is a good practice to declare the operator<() function in the same namespace.


For the sake of completeness after your edit, and as other have pointed out, you are trying to add a foo* where a foo is expected.

If you really want to deal with pointers, you may wrap the foo* into a smart pointer class (auto_ptr, shared_ptr, ...).

But note that in both case, you loose the benefit of the overloaded operator< which operates on foo, not on foo*.


struct Blah
{
    int x;
};

bool operator<(const Blah &a, const Blah &b)
{
    return a.x < b.x;
}

...

std::set<Blah> my_set;

However, I don't like overloading operator< unless it makes intuitive sense (does it really make sense to say that one Blah is "less than" another Blah?). If not, I usually provide a custom comparator function instead:

bool compareBlahs(const Blah &a, const Blah &b)
{
    return a.x < b.x;
}

...

std::set<Blah,compareBlahs> my_set;

You can overload the operator < inside the class also as,

struct foo 
{
  int key;
  bool operator < (const foo &other) const { return key < other.key; }
};

In your question, if you want to use set<foo> bar; as declaration then, you should insert value as,

bar.insert(*test);

But that won't be a good idea, as you are making redundant copy.

Tags:

C++

Struct

Set