Re: maps and constructors
On 2008-01-15 17:19, Hicham Mouline wrote:
Hello,
I am attempting to design a class:
class C {
std::map<double, const A> ma;
std::map<double, const B> ma;
.
public:
C(...);
};
The keys in the 2 maps are always identical. So I could choose:
std::map<double, const std::pair<A,B> >
or
std::map<double, const std::pair<A,B>* >
(ps: AFAIK, using a const-ref for the pair is impossible, but possible with
some boost classes)
Q1:
Is there a difference in memory usage, access speed or code
readability between the top choice and bottom ones?
Yes, if you use two maps you have to store the key twice, and when
retrieving items you have to do the lookup twice too. If you always
handle both A and B together there is not reason to keep them in
separate maps.
Consider also the implications on exception-safety, if you have two maps
and want to insert a new pair of A and B and you successfully insert the
A into its map but an exception is thrown when inserting B you must
remove the A from its map.
Q2:
Between the 2 bottom ones (storing the pair object in the map vs storing the
ptr)
Yes, at the very least you need the extra memory that is used to store
the pointers in addition to the space for the pair. Of course you might
be able to save memory using the pointer if multiple entries in the map
refer to the same pair of A and B.
Q3:
For users of class C, what sort of constructors should I offer?
C::C(const std::map<double, const std::pair<A,B>* >& )
Or, should I allow adding elements to the map after the object being
constructed?
C::add(double, const A&, const B&)
Depends on how you plan to use C, perhaps you should offer both?
--
Erik Wikstr?m