Hi
I need to maintain a <setof pointers to objects, and it must be
sorted based on the values of pointed objects, not pointer values. I
can achieve this easily by defining my own comparing predicate for the
<set>. Here is an example:
#include <string>
#include <set>
using namespace std;
class A
{
public:
A(const string& Name): m_Name(Name) {}
const string& Name() const { return m_Name; }
private:
string m_Name;
// Other members
// ...
};
class ptr_less
{
public:
bool operator()(const A* lhs, const A* rhs) const
{
return lhs->Name() < rhs->Name();
}
};
int main()
{
const string Names[] = { "alpha", "omega", "gamma", "beta",
"epsilon" };
// Create objects and fill 'S'
set<A*, ptr_lessS;
for (unsigned i = 0; i < sizeof(Names)/sizeof(Names[0]); ++i)
S.insert(new A(Names[i]));
// Use 'S' ...
// Delete objects in 'S'
set<A*, ptr_less>::const_iterator csi;
for (csi = S.begin(); csi != S.end(); ++csi)
delete *csi;
};
In this example pointers in the <setS will be sorted according to the
ascending order of names of pointed objects.
Now I want to find an obect in 'S' with name "gamma". How must I do
that? One way is to construct a dummy object with that name, and pass
its address to 'find' method of <set>. Here is an example:
A tempA("gamma");
S.find(&tempA);
Everything works ok, but creating a dummy object only for searching
purposes looks somewhat silly. Isn't there an elegant way to accomplish
this?
Thanks in advance
Martin