Link to home
Start Free TrialLog in
Avatar of Brillig
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
Avatar of GaryFx
GaryFx

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Brillig
Brillig

ASKER

 Thanks for the help.  I can't believe I had the for loop clauses swapped.  Based on a comment I saw in another thread I'm probably going to pick up a copy of Josuttis's STL book tomorrow.  But until then, do you have a recommendation on how to construct m_FooArray with the right size if it's a member variable?  Is there a way I can do it in the header or do I need to use reserve() in the constructor?

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
Avatar of Brillig

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.