Elena
Elena

Reputation: 39

How to copy a vector in a two dimensional vector

I'm trying to copy the content of an unidimensional vector in a two dimensional vector.

I've tried to use push_back()

vector<int> v;
vector<vector<int> > twov;

for (int i = 0; i < v.size(); i++)
    twov.push_back(v[i])

But, of course, I receive a the following error:

error: reference to type 'const value_type' (aka 'const std::__1::vector<int, std::__1::allocator<int> >') could not bind to an lvalue of type 'value_type'
  (aka 'int')

Could you help me?

Thanks in advance :)

Upvotes: 0

Views: 789

Answers (1)

R Sahu
R Sahu

Reputation: 206717

First thing you have decide is how should the elements of v be distributed to twov.

Say v has N elements. Is N expected to be equal to N1 x N2, where N1 is the number of rows and N2 the number of columns?

If the answer is yes, you can create twov with N1 1-D vectors in it to start with.

size_t N = v.size();
size_t N1 = <Some value>;
size_t N2 = N/N1;
assert(N1*N2 == N);

// Create twov with the appropriate elements.
vector<vector<int> > twov(N1, vector<int>(N2));

// Now copy the elements from v to twov
for (size_t i = 0; i < N1; ++i )
{
   for (size_t j = 0; j < N2; ++j )
   {
      twov[i][j] = v[i*N2+j];
   }
}

If the structure of twov is not as clean as above, you'll have to come up with a different logic for copying the elements of v to twov.

Upvotes: 1

Related Questions