Can I create a vector[][] from a vector[]

I have a unidimensional vector with 10 rows of data
I'd like to fill my bidimensional vector[][] with the unidimensional vecto.
Using the example, I will have a vector[10][1].
I dont want to fill the data using a loop
Any idea ? Is there some method to construc the new vector directly from the unidimensional initial vector ?
Thanks

If you don't want to *use* a loop, I'm not sure. But if you simply don't want to type the loop, you can do the following:

1
2
3
4
5
6
7
int const rows = 10;
int const columns = 10;

int uni[rows * columns];
int bi[rows][columns];

memcpy(bi, uni, sizeof(uni));

I'm guessing memcpy uses some kind of loop to do it's job internally.

Edit: An alternative that does not use a loop at all

Depending on what you're actually trying to do, you could avoid copying altogether and use a pointer to the unidimensional data to dereference as a bidimensional:

1
2
3
4
int TreatAs2D(int const *const uni, int const num_columns, int const column, int const row) {
    assert(row * column < sizeof(uni) / sizeof(uni[0])); // Don't go past your bounds
    return *(uni + (row * num_columns + column));
}


Now, instead of bi[1][2], you say TreatAs2D(uni, 10, 1, 2)

The second parameter is what tells TreatAs2D how many columns wide to treat your new "2D" array.
Last edited on
Thanks, I'm going to try it.
Let me see if I got it right!

The vector container has a ctor that allow you to fill elements in the vector like;
1
2
// all the includes and stuff...
vector<double> my_vec(10, .5);


Right there is a vector of ten doubles filled with value .5 (0.5) each. Now for what I understand you want to fill a matrix of 10 elements initilized with another vector, say, our 'my_vec' in this example. If so, it could be done like this:

1
2
3
4
5
6
7
8
9
10
11
typedef vector<vector<double>> Matrix;
Matrix mat(10, my_vec); // here is ur matrix filled with my_vec, without looping.
typedef Matrix::size_type index;

//Now to inspect the matrix you do need some looping
for(index i(0); i < mat.size(); ++i)
{
		for(index j(0); j < mat[0].size(); ++j)
			cout << mat[i][j] << ' '; // Note you use [][] sintax!
		endl(cout);
}

I'd prefer to wrap all that in a class of course, like this is horrible code but helps ilustrating...
Hope it helps!






Topic archived. No new replies allowed.