On Fri, 18 Jul 2003 21:11:56 -0400, Parnakunj wrote:
> Can I use an STL set<> container to store pointers to objects and
> ensure that it does not store to objects(different addresses) with the
> same values for the member variables of the class.
>
> eg:
>
[snipped - editted version below].
>
>
> Here the behavior that I want is that setA should only contain object
> pointed by A1 *OR* object pointed by A2, not both.
>
Hi Parna,
Yes, you can do this. The answer is to provide a comparison operator for
your set. Tweaking your code to do this gives
#include <iostream>
#include <set> //*
using namespace std; //*

To avoid noise from the group
class A {
private:
int a;
int b;
public:
A(int _a, int _b)
{
a = _a;
b = _b;
}
// Comparison operator for A's
bool operator<(const A& rhs) const
{
return (a < rhs.a || (a == rhs.a && b < rhs.b));
}
};
// Use A:

perator< for comparison
struct compare
{
bool operator()(const A* lhs, const A* rhs) const
{
return *lhs < *rhs;
}
};
int main()
{
// Give an explicit comparator to set.
set<A*, compare> setA;
A *A1 = new A(10,20);
A *A2 = new A(10,20);
cout << A1 << " " << A2 << "\n";
setA.insert(A1);
setA.insert(A2);
cout << setA.size() << "\n";
cout << *setA.begin() << "\n";
return 0;
}
This gives me
0x804aa70 0x804aa80
1
0x804aa70
so only the first A object is added as you wished. Note that if you're
going to do this you need to worry about the ownership of the pointers as
doing something equivalent to
setA.insert(new A(10, 20));
could give a memory leak if the pointer is not added. Your probably best
avoiding this by using something like boost::smart_ptr instead of plain
pointers, see
http://www.boost.org.
The operator< needs to satisfy various properties to work properly,
namely:
1. Antisymmetric, ie. if a < b is true then b < a is false;
2. Transitive ie if a < b and b < c then a < c
3. Irreflexive ie a < a is always false.
Hope that helps,
Ian
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]