3

I'm trying to define the values of a 'row' or 1D vector and then push_back that row into a 2D vector. I've tried a couple different things that don't throw errors but also don't seem to work. Code below:

#include <vector>
#include <iostream>
using std::vector;

#define HEIGHT 5
#define WIDTH 3

// 2D VECTOR ARRAY EXAMPLE

int main() {
vector<vector<double> > array2D;
vector<double> currentRow;

// Set up sizes. (HEIGHT x WIDTH)
// 2D resize
array2D.resize(HEIGHT);
for (int i = 0; i < HEIGHT; ++i)
{
  array2D[i].resize(WIDTH);
}
// Try putting some values in
array2D[1][2] = 6.0; // this works
array2D[2].push_back(45); // this value doesn't appear in vector output.  Why?

// 1D resize
currentRow.resize(3);

// Insert values into row
currentRow[0] = 1;
currentRow[1] = 12.76;
currentRow[2] = 3;

// Push row into 2D array
array2D.push_back(currentRow); // this row doesn't appear in value output.  Why?

// Output all values
for (int i = 0; i < HEIGHT; ++i)
{ 
  for (int j = 0; j < WIDTH; ++j)
    {  
        std::cout << array2D[i][j] << '\t';
  }
  std::cout << std::endl;
 }
 return 0;
}
ProGirlXOXO
  • 2,170
  • 6
  • 25
  • 47

3 Answers3

7

By the time you push_back currentRow, array2D already contains HEIGHT rows and after the push_back it will contain HEIGHT+1 rows. You just don't show the last one you added, only the first HEIGHT rows.

sellibitze
  • 27,611
  • 3
  • 75
  • 95
3

push_back() appends an item to the end of the vector. If the vector contained WIDTH items, it contains WIDTH+1 items after the push_back().

When you print the contents of the vector, you only print the first WIDTH items, even if the vector contains more, so you don't see the additional items.

You can find out how many items are in a vector with the size() method.

sth
  • 222,467
  • 53
  • 283
  • 367
1

You are using resize when you actually want to use reserve method instead. The thing is that resize does change the content of the vector, while reserve just changes the storage capacity. So if you resize a vector to N elements and then push some elements into it, they will be pushed in positions N, N + 1, etc, while if you just reserve size for N elements, they will be pushed in positions 0, 1, etc, which is what you seem to want.

Win32
  • 1,109
  • 10
  • 12