Convert int[n][n] to vector<vector<int>>

Viewed 197

We can easily convert an array to a vector with the following:

int a[n];

vector<int> b = vector(a, a + n);

I want to work with matrix, what if I want to convert :

int a[n][n];

to

vector<vector<int>> b = ... // from a 

with b.size() = n and b[0...n-1].size() = n ?


Alternatively I am okay with a solution converting

std::vector< std::array<int, n> > a;
a.reserve(n);

vector<vector<int>> b = ... // from a
1 Answers

I doubt that vector of vector is the best choice of the container for your use case, but if it's out of your control something like this should work:

int a[n][n];
std::vector<std::vector<int>> v;
v.reserve(n);
for (int *arr : a) {
    v.emplace_back(arr, arr + n);
}
Related