Re: need help creating a two dimensional vector that holds pointers
of a user defined type
On Apr 8, 5:46 am, dwightarmyofchampi...@hotmail.com wrote:
On Apr 7, 11:13 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
for (std::vector<ABC*>::iterator it = vec.begin();
it != vec.end();
it++)
{
delete *it; *it = 0;
I can understand deleting (since you allocated it using 'new'), but why
do you care to set it to 0? The vector is going to be destroyed righ=
t
after the destructor's body finishes...
I never really understood the rule about setting pointers to zero, it
was always something my professor told me to do "to be on the safe
side." So I just ended up setting all my pointers to zero after delete
statements without really giving much thought as to what it did.
So, when do need to set the opointer equal to zero and when is it
unnecessary?
You only need to set a pointer to zero (or NULL) if the pointer will
continue to exist for some time, but you don't have a better value for
it.
Setting a pointer to zero in a destructor is always pointless, because
the pointer itself will shortly after cease to exist.
It's a 'vector<ABC*>', of course! So, you need to push an instance o=
f
that object onto your 'vec' before entering the inner loop:
for (int i = 0; i < 7; ++i)
{
vec.push_back(vector<ABC*>()); // now you have i-th ele=
ment
for (int j = 0; j < 5; ++j)
vec[i].push_back(new ABC(j));
}
OK, now here is something I am totally clueless about:
vector<ABC*>()
What is with the two parentheses at the end? Does that mean that it's
an empty vector?
Technically it means that it is a (temporary) default-constructed
vector. A default-constructed vector is an empty vector, so the answer
to your question is Yes.
Is there anything we could put in those parentheses
if we wanted to?
Yes, you can specify the number f elements you want the vector to
initially have (and as second argument you can specify an element to
use as a basis to construct the initial elements from).
Bart v Ingen Schenau