Re: need help creating a two dimensional vector that holds pointers
of a user defined type
On Apr 8, 5:27 am, Sam <s...@email-scan.com> wrote:
dwightarmyofchampi...@hotmail.com writes:
// vec is a vector of a vector of pointers to ABC objects
std::vector< std::vector<ABC*> > vec;
[...]
Even better, you should redeclare the whole object as:
std::vector< std::vector<ABC> >
and let the STL do all the allocation and deallocation for you.
If he can. It's not clear whether he's using pointers because
he's gotten bad habits from Java, or because the objects he's
pointing to aren't copiable. But in general: use (and copy)
objects when you can, use pointers (and dynamic allocation) when
you have to.
One thing to keep in mind is that std::vector is likely to do
quite a bit of internal memory copies, if your vector grows
and shrinks by a large amount. If your vector gets large
enough, you're going to take a performance hit. Generally,
vectors are designed for usage cases where you typically
allocate them once, right up front, and don't change their
size, until you no longer need the vector and you destroy it.
I've not found that to be the case. The standard requires
amortized constant time for push_back, and most implementations
seem to use a fairly large multiplier (between 1.5 and 2), which
means that reallocations and the subsequent copies are fairly
rare events. (On the other hand, you can waste a fair amount of
memory.) If he finds that initializing the vectors is a
performance issue, and he knows the final size, he can always
use reserve to ensure that there is no reallocation or copying
during the initialization. If the objects in the vector are
cheap to default initialize (the case with pointers and the
basic types), it's also worth considering initially creating the
vectors with the final size, and then using [] to insert the
actual initial values. (At least on the one implementation
where I measured it, resize() followed by [] was significantly
faster than reserve() followed by push_back(). Which surprised
me a bit, but that's what the measurements said.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34