# How to flatten a 2-Dimensional vector in C++

Hello Guys, In this tutorial we are going to learn how to flatten a 2-Dimensional vector in C++. Before we get into this let’s discuss what is a 2-D vector, so it is a vector of vectors. Let’s say we have as a 2-D then it can be defined as

`vector<vector<int> >v;`

For example,

`v= {{2,3,4};{1,5,3};{6,7};{};{1}};`

Few things are to be noted here,

• Vectors in ‘v’ can have different sizes.
• The size of a vector can be zero.

## Algorithm for flattening a 2-D vector in C++

There is a standard approach to flatten a 2-D vector is using iterators (two-pointers) but with this, I will discuss one more way to do this.
Let’s see the standard one first;

• First, I would recommend you to read this post on Classes and objects, because we will be using this in the implementation of this algorithm.
• We define two pointers one for rows and another for columns.
• Then we set them to the first element of the first vector and update them iteratively.
• And finally terminate the program after printing all elements.

#### Code

```#include<bits/stdc++.h>
using namespace std;

class Flatten2DVector{
public:
// a temporary copy of given vector, will use this furthur to avoid corruptions in original data
vector<vector<int>> temp;
int row, col;//two pointers
Flatten2DVector(vector<vector<int>>& v) {
temp = v;
row = 0;// initialising pointers to first index
col = 0;
}
// returns the elements from temp vector
int next() {
forward();
return temp[row][col++];
}
// checks whether next element is possible or not
// also takes care of skipping the vectors of zero size
bool hasNext() {
forward();
return (row < temp.size());
}
// helps to move forward in the vector
void forward() {
while ((row < temp.size()) && (col>=temp[row].size())) {
row++;
col = 0;
}
}
};

int main(){
vector<vector<int>>v;
v={{1,3},{2,9,5,5},{},{4,5,6},{8}};//given 2Dvector
Flatten2DVector it(v); // Class which has iterator(it) as his object
// check if next element is posible or not, if possible print it
while (it.hasNext()) {
cout << it.next() << " ";
}
cout<<endl;
return 0;
}```

Now let’s discuss another approach;

This is a very simple approach where I will take all elements of the original 2D vector into a new 1D vector using nested for loops. And then print the new vector.

#### Code

```#include<bits/stdc++.h>
using namespace std;

int main(){
vector<vector<int>>v;
vector<int>n;//new 1D vector
v={{1,3},{2,9,5,5},{},{4,5,6},{8}};//given 2Dvector
// using nested for loops to construct a new 1D vector
for(int i=0; i<v.size(); i++){
for(int j=0; j<v[i].size(); j++){
n.push_back(v[i][j]);
}
}
// Printing New vector
for(int i=0; i<n.size(); i++){
cout<<n[i]<<" ";
}
cout<<endl;
return 0;
}```

Now, look at the output for both implementations.

##### Output
`1 3 2 9 5 5 4 5 6 8`

This is it for this tutorial.