Topic: make finding in associative containers templated members?
Author: Ian Haggard <ian@shellus.com>
Date: 1997/02/03 Raw View
[I sent this earlier but it appears to have been clipped by some mailer
between here and there, so I'm re-sending it]
I have a couple places in my code that resemble the following:
class NamedObject {
// etc.
public
const string& name();
// etc.
};
class NameCompare {
public:
bool operator()(const NamedObject& lhs,const NamedObject& rhs)
{ return lhs.name()<rhs.name(); }
};
set<NamedObject,NameCompare> objectSet;
And I want to execute code like this:
string name;
cin >> name;
NamedObject& namedObj=*(objectSet.find(name));
I find that there are only two ways to do this reasonably efficiently.
The first is to make objectSet into a map, with the name being the key
and the value being the NamedObject. But I find the redundancy
unappealing aesthetically, a waste of memory, and a source of potential
error. The second method of doing this is a really disgusting hack that
only works on classes whose source code and interface I can modify.
string name;
cin >> name;
NamedObject tmpObj;
tmpObj.setName(name);
NamedObject& namedObj=*(objectSet.find(tmpObj));
The only aesthetically pleasing solution I can think of would be to make
find a templated member function of the associative container classes.
In other words:
template<class KeyComparable> iterator find(const KeyComparable& k);
Then, I could accomplish my goal by merely overloading the function-call
operator in the class NameCompare like so:
class NameCompare {
public:
bool operator()(const NamedObject& lhs,const NamedObject& rhs)
{ return lhs.name()<rhs.name(); }
bool operator()(const string& lhs,const NamedObject& rhs)
{ return lhs<rhs.name(); }
bool operator()(const NamedObject& lhs,const string& rhs)
{ return lhs.name()<rhs; }
};
Is there perchance any other way to accomplish my goal? If not, I'd
like to propose that find, upper_bound, lower_bound, and equal_range be
made templated member functions of the associative container classes.
--
Ian Haggard || ian@shellus.com (work) || IanHaggard@juno.com (home)
Linux -- "Oh, no, Mr Bill!" || #define employer_opinion !my_opinion
[ comp.std.c++ is moderated. To submit articles: try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]