October 29th, 2013, 04:44 PM
vector::assign in two dimensions
If I have a one-dimensional array of length 10, vector<int> x, and I want to assign all the elements to value 5, then I can do the following:
(I can also do this in x's constructor, but in my scenario I want to repeatedly assign x's elements in a loop, without having to construct a new vector in memory each time.)
If I now have a two-dimensional vector, vector<vector<int> > y, and I want to assign the first vector to length 20, the second vector to length 10, and each element in the second vector to value 5, then I can do the following:
But is it possible to do this without the loop? Can I make the two-dimensional assignment in just one line, in the same way that the one-dimensional assignment was made?
vector<vector<int> > y(20, vector<int> (10));
for (int i = 0; i < 20; i++)
Perhaps it would like something like the following, which is not correct but illustrates what I mean:
Another way of doing this would be the following:
y.assign(20, assign(10, 5));
But wouldn't this cause the memory in the second array to be dynamically allocated each time? I don't want to do this - I want to keep the same memory, but just assign the elements to 5.
y.assign(20, vector<int> (10, 5));
Click Here to Expand Forum to Full Width