Reputation: 8506
How can I customize the comparison of elements in a ptr_container? Using a ptr_set, I would like to define a function that checks for equality of elements. However, defining
bool operator==(const Foo& other) (or a friend function)
does not work. It just won't be invoked, although boost's unordered containers, on the other side, are aware of overloaded operator==s. Predicates a la:
struct FooEq
{
bool operator()(const Foo& foo1, const Foo& foo2) const
};
don't work either and I cannot find a reference that describes how to accomplish this.
struct Foo
{
Foo(int i, int j) : _i(i), _j(j) {}
bool operator<(const Foo& other) const { return this->_i < other._i; }
bool operator==(const Foo& other) const
{
std::cout << "== involed";
return this->_j == other._j;
}
int _i;
int _j;
};
boost::ptr_set<Foo> foos;
std::cout << foos.size() << "\n";
foos.insert(new Foo(1, 2));
std::cout << foos.size() << "\n";
foos.insert(new Foo(2, 2));
std::cout << foos.size() << "\n";
The foos are supposed to be equal since for both j == 2 holds.
Thanks in advance
Upvotes: 1
Views: 406
Reputation: 12814
Set uses the < operator to insert items and test for equivalence (which is not quite the same as equality). This operator must define a strict weak ordering. Set will not use the == operator.
Quoted from the description for set:
Compare: Comparison class: A class that takes two arguments of the same type as the container elements and returns a bool. The expression comp(a,b), where comp is an object of this comparison class and a and b are elements of the container, shall return true if a is to be placed at an earlier position than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). This defaults to less, which returns the same as applying the less-than operator (a
If you elaborated what you are trying to accomplish, I could offer suggestions for a better container.
Upvotes: 1
Reputation: 341
I couldn't understand your situation exactly. However, You can use std::set . It doesn't support duplication.
set<shared_ptr<T>>
is really helpful in your case.
Upvotes: 0