user1485086
user1485086

Reputation: 3

Convert a 1D Array to 2D Vector c++

Could someone help me to write a logic that converts a ID array to a 2D vector.

something like

int array[] = {1, 4, 5, 7, 9, 3}; // dynamic array
vector <vector int> ex;

How can I now place the values in ex from array.. so that it forms 2 vectors each of 3 values?

I have searched for help with no use and have tried it myself as below:

for(int i=0; i<2; i++)
{   
        rowTemp_ex.assign(array, array+3));
 ex.push_back(rowTemp_ex);
 rowTemp_ex.erase(rowTemp_ex.begin() , rowTemp_ex.end());
}

Upvotes: 0

Views: 3363

Answers (3)

jrok
jrok

Reputation: 55395

You're on the right track but made an error in your for loop:

rowTemp_ex.assign(array, array+3));

That would assign the same part of the array each iteration. You need to multiply the size of the row (3) with i:

rowTemp_ex.assign(array + i * 3, array + (i * 3) + 3));

i = 0:      0*3                  0*3+3
i = 1:                            1*3                   1*3 + 3
array:    [  0  ][  1  ][   2  ][   3  ][  4   ][  5  ] [one past the end]

The call to vector::erase is redundant, vector::assign in next iteration will discard previous content anyway.

Here's something more general that will also deal with possible odd elements (untested):

const size_t arr_size = N;
const size_t n_cols = M;
const size_t n_rows = arr_size / n_cols;
const size_t n_odd = arr_size % n_cols;

int arr[arr_size] = { .... };

int* begin = arr;
int* end = arr + (n_rows * n_cols);

while( begin != end ) {
    ex.push_back(std::vector<int>(begin, begin + n_cols));
    begin += n_cols;
}

if (n_odd)
    ex.push_back(std::vector<int>(begin, begin + n_odd));

Upvotes: 1

leemes
leemes

Reputation: 45675

Assuming that you want always three vectors of the size two each, and that the 2D vectors are aligned in pairs in your C-array, do the following:

int array[] = {1, 4, 5, 7, 9, 3}; // dynamic array
vector<vector<int> > ex;

for(int i = 0; i < 3; ++i)
{
    vector<int> tmp;
    tmp.push_back(array[2*i]);
    tmp.push_back(array[2*i+1]);
    ex.push_back(tmp);
}

Upvotes: 0

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234444

First, compute how many row-vectors there will be. If each one has three elements, the total is the size of the array divided by 3.

template <typename T, std::size_t N>
std::size_t size(T(&)[N]) { return N; }

int number_of_rows = size(array) / 3;

Now create a vector with that number of row-vectors with three elements each:

std::vector<std::vector<int> > v(number_of_rows, std::vector<int>(3));

And then go through the original array and fill up each cell of the result, using integer division and remainder operations:

for(int i = 0; i < size(array); ++i) {
    v[i / 3][i % 3] = array[i];
}

Upvotes: 1

Related Questions