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:

Download  Run Code

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:

Download  Run Code

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.

Download  Run Code

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