I have a struct which has a unique key. I want to insert instances of these structs into a set. I know that to do this the < operator has to be overloaded so that set can make a comparison in order to do the insertion.
The following does not work:
#include <iostream> #include <set> using namespace std; struct foo { int key; }; bool operator<(const foo& lhs, const foo& rhs) { return lhs.key < rhs.key; } set<foo> bar; int main() { foo *test = new foo; test->key = 0; bar.insert(test); }
Yes if the structure is of the same type.
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).
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*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With