Re: need help creating a two dimensional vector that holds pointers
of a user defined type
I am having trouble with two-dimensional vectors. In my old code I had
a vector in my class definition that looked like this:
So, it's a non-static data member, right?
...which means I am declaring a vector whose elements will contain
pointers to ABC objects.
...and in my constructor I have:
// make sure vector is empty before populating it
Why, FCOL? You're in the constructor. The vector has just been
constructed. How can it have anything?
I can understand having
here somewhere, just for kicks, but 'clear'?
for (int i = 0; i < 5; i++)
ABC* abcobject1 = new ABC(i);
And why can't you just do
instead of defining a local to this loop variable? Just curious about
...and in my destructor I have:
for (std::vector<ABC*>::iterator it = vec.begin();
it != vec.end();
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 right
after the destructor's body finishes...
This is all well and good and appears to work OK. Now, let's suppose
that I want to make vec be a two-dimensional vector instead of a one-
dimensional vector. That is, the definition in my header file now
looks like this:
// 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);
You can't index in a vector that doesn't have anything. 'vec' is empty
when you start, so evaluating 'vec[i]' has undefined behaviour.
When the loop first iterates (i and j both equal zero) how can it
push_back an item onto vec when vec itself doesn't exist yet?
Right. It can't.
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
What is the type of 'vec'? What do you expect there? Come on, you
can do it...
It's a 'vector<ABC*>', of course! So, you need to push an instance of
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 element
for (int j = 0; j < 5; ++j)
Oh, and my destructor looks like this:
for (std::vector< std::vector<ABC*> >::iterator itOuter = vec.begin();
itOuter != vec.end();
for (std::vector<ABC*>::iterator itInner = (*itOuter).begin();
itInner != (*itOuter).end();
delete *itInner; *itInner = 0;
I have no idea if that's correct, since I haven't gotten that far yet.
Seems fine except for the unnecessary assigning of the 0.
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask