Home > front end >  Convert Vector of integers into 2d array of type const int* const*
Convert Vector of integers into 2d array of type const int* const*

Time:04-03

I have a vector of integers that I should make into a 2d array. The row and column size of the new 2d array are given by user and contain all the integers from previous vector. The 2d array should be of type const int* const*. How do I do this in c ?

CodePudding user response:

Try something like this:

std::vector<int> nums;
// fill nums as needed...

int rows, cols;
std::cin >> rows >> cols;

if ((rows * cols) > nums.size())
    // error

int** arr = new int*[rows];
for (int row = 0; row < rows;   row) {
    arr[row] = new int[cols];
    for (int col = 0; col < cols;   col) {
        arr[row][col] = nums[(row*cols) col];
    }
}

// use arr as needed...

for (int row = 0; row < rows;   row) {
    delete[] arr[row];
}
delete[] arr;
  • Related