Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a set of structs in C++

Tags:

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); } 
like image 928
node ninja Avatar asked Apr 28 '11 09:04

node ninja


People also ask

Can we assign one structure to another?

Yes if the structure is of the same type.

How do structs work in C?

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.).


1 Answers

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*.

like image 92
ereOn Avatar answered Sep 18 '22 17:09

ereOn