Reputation: 521
I have some classes, one for example is something like:
class foo {
private:
int number;
...
public:
foo(int set_number):number(set_number) {}
...
bool operator<(const foo &myfoo) const
{
return (number < myfoo.number ? 1 : 0);
}
/* operator < */
bool operator==(const foo &myfoo) const
{
return (number == myfoo.number ? 1 : 0);
}
/* operator == */
...
};
And I was using something similar to this class with set:
class hello {
private:
set<foo*> list;
set<int> int_list;
...
public:
...
fillList(void)
{
for(int i=0; i<10; i++)
{
list.insert(new foo(i));
int_list.insert(i);
}
}
...
};
Ok, so when I print the result I get:
int_list: 0, 1, 2, 3, 4, ...
list: 0, 6, 4, 5, ... (Using a method to print the attribute "number" from the object foo).
Obviusly the second is not ok. I guess it has to do with the fact that set is made of pointers, not of objects.
Now, should I use my set just like set< foo > ? Or is there a solution for this using pointers ?. Maybe I can overload the operators using something like:
bool operator<(const *foo myvar, const *foo myvar2);
I was using this "set< foo* >". Because I was taught to use this way in vector< type > objects.
What's the best option ?
Upvotes: 0
Views: 75
Reputation: 7344
If you want a custom sorting in set, you can't override < operator because:
set<foo*>
Its a set of pointers. Use instead:
set<foo*, compare>
And:
struct compare {
bool operator() (const foo * lhs, const foo * rhs) const{
return lhs->operator<(*rhs);
}
};
Your set is sorting pointers. If you add compare
to set<foo*, compare>
, you force to use the < operator
of the pointed class.
Just use set<foo>
and remove new from list.insert(new foo(i));
.
Upvotes: 1