Oct 29, 2012 at 1:45pm Oct 29, 2012 at 1:45pm UTC
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 Oct 29, 2012 at 2:28pm Oct 29, 2012 at 2:28pm UTC
Oct 29, 2012 at 3:34pm Oct 29, 2012 at 3:34pm UTC
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;
Oct 29, 2012 at 3:52pm Oct 29, 2012 at 3:52pm UTC
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??
Oct 29, 2012 at 5:46pm Oct 29, 2012 at 5:46pm UTC
lets say you want a matrix like this:
Just construct your rows, one at a time, then push them into the 2D vector like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <vector>
#include <iostream>
int main()
{
typedef std::vector<int > Row;
std::vector<Row> 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 Oct 29, 2012 at 5:49pm Oct 29, 2012 at 5:49pm UTC