Convert a vector of vectors to an array in C++
This post will discuss how to convert a vector of vectors to a single-dimensional or a two-dimensional array in C++.
1. Convert Vector to 2D Array
The idea is to allocate a new 2D array of dimensions of the given vector, and copy all elements from the vector to the new array using a regular for loop. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> #include <vector> #include <numeric> int main() { const int m = 3, n = 4; std::vector<std::vector<int>> mat(m, std::vector<int>(n, 1)); int arr[m][n]; int k = 0; for (unsigned i = 0; i < m; i++) { for (unsigned j = 0; j < n; j++) { arr[i][j] = mat[i][j]; } } for (unsigned i = 0; i < m; i++) { for (unsigned j = 0; j < n; j++) { std::cout << arr[i][j] << ' '; } std::cout << std::endl; } return 0; } |
Output:
1 1 1 1
1 1 1 1
1 1 1 1
2. Convert Vector to 1D Array
To convert a vector of vectors to a single-dimensional array, we can allocate an array of size equal to the total number of elements in the vector, and copy all elements from the vector to the new array using the enhanced for-loop. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <vector> int main() { const int m = 3, n = 4; std::vector<std::vector<int>> mat(m, std::vector<int>(n, 1)); int arr[m*n]; int k = 0; for (auto &vec: mat) { for (auto &e: vec) { arr[k++] = e; } } for (int i = 0; i < m*n; i++) { std::cout << arr[i] << ' '; } return 0; } |
Output:
1 1 1 1 1 1 1 1 1 1 1 1
Alternatively, we can use the std::vector::data member function to flatten a vector. It returns a pointer to the memory location used by the vector for storing its elements. Since a vector is stored in a contiguous storage location, the returned pointer can access an array element using the index.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <vector> #include <numeric> int main() { const int m = 3, n = 4; std::vector<std::vector<int>> mat(m, std::vector<int>(n, 1)); std::vector<int> flattened = std::accumulate(mat.begin(), mat.end(), std::vector<int>(), [](std::vector<int> &x, std::vector<int> &y) { x.insert(x.end(), y.begin(), y.end()); return x; }); auto ptr = flattened.data(); for (int i = 0; i < m*n; i++) { std::cout << ptr[i] << ' '; } return 0; } |
Output:
1 1 1 1 1 1 1 1 1 1 1 1
That’s all about converting a vector of vectors to a single-dimensional or a two-dimensional array in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)