Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ Vectors

  1. May 10, 2012 #1
    I decided to make the switch from C to C++ and I'm having trouble with vectors. In C, I prefer to use dynamically allocated arrays when doing multidimensional arrays. But in C++, I know that there is the new function which replaced malloc. I read that when dealing with multidimensional arrays in C++, ideally a vector would be used.

    So my question is, can someone just provide a quick run through of creating a 2D vector, changing the size of the vector, and then deleting it? Thank you in advance, any help is much appreciated.
  2. jcsd
  3. May 10, 2012 #2


    User Avatar

    Staff: Mentor

    See the following thread for an example:


    One way to change the number of rows in the example linked above:
    Code (Text):

    mymatrix.resize (numrows_new);
    If this adds new rows (i.e. you increase the size), they'll be empty (zero length). If you want the new rows to have the same size as the existing ones:
    Code (Text):

    mymatrix.resize (numrows_new, vector<double>(numcols));
    In either case, if you decrease the number of rows, they're "chopped off" the end (bottom) of the matrix.
    To change the number of columns, you have to change the size of each row:

    Code (Text):

    for (int row=0; row<numrows; row++)
    Last edited: May 11, 2012
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook