views:

73

answers:

2

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

+1  A: 
JoshD
But why has ptr_set a template parameter 'compare' then?
jena
@jena: that parameter is used to specify the < operator. If none is provided it defaults to the < operator.
JoshD
I see, thanks for clarification.
jena
@jena: if the answer was helpful for you, you can vote it up. I'd appreciate it :)
JoshD
Of course :) Thanks again
jena
A: 

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.

Bander
I did that before and decided to use ptr_set to hide the pointers (the interace allows access the elements of the container). So I could either ignore that and go back to using std::set or explicitly check whether a given element is already in the ptr_container. Hm
jena