Brillig
asked on
2D vector usage
I'm having a problem with some multidimensional vectors. The code looks something like this:
protected:
vector< vector<int> > m_FooArray;
m_FooArray.clear();
for( int i = 0; i++; i < MAX1 )
{
m_FooArray[i].assign( MAX2, 0 ); // This works
}
m_FooArray[2][2] = 4; // This compiles fine, but bombs on execution
m_FooArray is a member of a base class and used in the constructor of the derived classes, in case that matters. Bacically I want to know what's wrong with the line that bombs and if there's an equivalent notation that I can use. I have a large amount of data that needs to be hard coded, so the simpler the notation the better. (Reading from files is undesirable in this case, though I may end up doing it anyway.)
Thanks in advance.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You should be able to do:
vector< vector<int> > m_FooArray(MAX1);
assuming MAX1 is defined at that point.
If you did it later, you'd have to use resize(), not reserve(). The difference is that reserve() doesn't actually construct the entries, nor does it change the size() of the array. All it does is allocate raw storage, so that you're not wasting a lot of time allocate one element at a time. resize(), on the other hand, will change the size() of the array, and when it increases the size of the array, it will call the default constuctor on the new elements.
But the declaration above ought to work more easily.
Gary
vector< vector<int> > m_FooArray(MAX1);
assuming MAX1 is defined at that point.
If you did it later, you'd have to use resize(), not reserve(). The difference is that reserve() doesn't actually construct the entries, nor does it change the size() of the array. All it does is allocate raw storage, so that you're not wasting a lot of time allocate one element at a time. resize(), on the other hand, will change the size() of the array, and when it increases the size of the array, it will call the default constuctor on the new elements.
But the declaration above ought to work more easily.
Gary
ASKER
Thanks. That should fix my (current) problem. I just got back from buying Josuttis' STL book. Looks like there's a lot of STL stuff I need to brush up on. Thanks again for the help.
ASKER