Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push_back 1D Vector as Row into 2D Vector Array

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;
}
like image 264
ProGirlXOXO Avatar asked Jan 20 '26 13:01

ProGirlXOXO


1 Answers

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.

like image 182
sellibitze Avatar answered Jan 23 '26 02:01

sellibitze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!