Hi;

I want to fill a 2D vector by some floats. can i use list.push_back again? How?for example I want to send 4.5 to the ithrow and jth column.
Last edited on
If you want to push back something to the ith row then use this:
`my_vector[i].push_back(4.5);`

However, if you just want to assign 4.5 to the ith row and jth column, then do this:
`my_vector[i][j] = 4.5;`
How do i define my vector if i use it in this way?? 1D or 2D?

`my_vector[i].push_back(4.5);`
does this line show in which column 4.5 is??
lets say you want a matrix like this:
 ```0 1 2 3 4 5 6 7 8```

Just construct your rows, one at a time, then push them into the 2D vector like so:
 ``12345678910111213141516171819202122232425`` ``````#include #include int main() { typedef std::vector Row; std::vector my_vector; for (int row = 0; row < 3; ++row) { Row my_row; for (int col = 0; col < 3; ++col) my_row.push_back( row*3 + col ); my_vector.push_back(my_row); } for (int row = 0; row < 3; ++row) { for (int col = 0; col < 3; ++col) std::cout << my_vector[row][col] << ' '; std::cout << std::endl; } }`````` ```0 1 2 3 4 5 6 7 8```

I like to use the Typedef when doing this because it makes it very clear that we have a vector of rows. `std::vector< std::vector<int> >` is too verbose for me.
Last edited on
Topic archived. No new replies allowed.