Re: need help creating a two dimensional vector that holds pointers
of a user defined type
This is a MIME GnuPG-signed message. If you see this text, it means that
your E-mail or Usenet software does not support MIME signed messages.
The Internet standard for MIME PGP messages, RFC 2015, was published in 1996.
To open this message correctly you will need to install E-mail or Usenet
software that supports modern Internet standards.
--=_mimegpg-commodore.email-scan.com-24634-1239161268-0001
Content-Type: text/plain; format=flowed; charset="US-ASCII"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit
dwightarmyofchampions@hotmail.com writes:
// vec is a vector of a vector of pointers to ABC objects
std::vector< std::vector<ABC*> > vec;
OK, now here's where I'm messing up. My constructor looks like this:
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 5; j++)
{
ABC* abcobject1 = new ABC(j);
vec[i].push_back(abcobject1);
}
}
When the loop first iterates (i and j both equal zero) how can it
push_back an item onto vec[0] when vec[0] itself doesn't exist yet? I
think there needs to be a vec.push_back(...) line somewhere earlier,
but I don't know where and what should be pushed back. Can someone
help me?
vec.push_back(std::vector<ABC *>());
The elements of vec are std::vector<ABC *>. So that's what you push back
into it.
Oh, and my destructor looks like this:
for (std::vector< std::vector<ABC*> >::iterator itOuter = vec.begin();
itOuter != vec.end();
itOuter++)
{
for (std::vector<ABC*>::iterator itInner = (*itOuter).begin();
itInner != (*itOuter).end();
itInner++)
{
delete *itInner; *itInner = 0;
}
}
I have no idea if that's correct, since I haven't gotten that far yet.
That looks reasonable to me.
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.
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.
--=_mimegpg-commodore.email-scan.com-24634-1239161268-0001
Content-Type: application/pgp-signature
Content-Transfer-Encoding: 7bit
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEABECAAYFAkncGbQACgkQx9p3GYHlUOID0QCfRfwxgntc4gPHccgOFexI0gqh
U8kAn2bXt8SwQEcWvmlblgULSiYsoHED
=ALZE
-----END PGP SIGNATURE-----
--=_mimegpg-commodore.email-scan.com-24634-1239161268-0001--