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:

Code:

vector<int> x(10);
x.assign(10, 5);

(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?

Perhaps it would like something like the following, which is not correct but illustrates what I mean:

Code:

y.assign(20, assign(10, 5));

Another way of doing this would be the following:

Code:

y.assign(20, vector<int> (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.

Any thoughts?

Thanks!

October 30th, 2013, 03:01 AM

superbonzo

Re: vector::assign in two dimensions

Quote:

Originally Posted by karnavor

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?

If your goal is just to turn that loop into one line, then write a function.
If your goal is to access the 2d vector as a contiguous 1d memory region, then it's not possible as it is. To do so, you should either use a 1d vector ( 2d elements can be accessed by simple indexing arithmetic, as a free function or incapsulated inside a class ), or use a specialized allocator ( the boost library has one: the pool allocator ) or replace the vector with some ready made matrix class ( there are many libraries out there ).

in other words, what are you trying to achieve by assigning elements "without the loop" ?

Quote:

Originally Posted by karnavor

But wouldn't this cause the memory in the second array to be dynamically allocated each time?