简体   繁体   中英

Convert Vector of integers into 2d array of type const int* const*

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM