# How to return a 2D vector in C++?

Returning a 2D vector is exactly the same as returning a primitive datatype in C++. The syntax of a function that returns the 2D vector is

``````vector<vector<int>> ReturnVector(){
vector<vector<int>> V;
.......
.......
return V;
}``````

The above function returns a copy of V.

Example,

``````#include<iostream>
#include<vector>
using namespace std;

// the functions returns a 2D vector
// of size n X n and all elements
// equals to x
vector<vector<int>> Return2DVector(int n, int x){
vector<vector<int>> v;

for(int i=0;i<n;++i){

v.push_back(vector<int>());
for(int j=0;j<n;++j){
v[i].push_back(x);
}

}

return v;
}

int main()
{
vector<vector<int>> v;
int n,x;

n = 4;
x = 2;
v = Return2DVector(n,x);

for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
cout<<v[i][j]<<' ';
}
cout<<endl;
}

}``````

Output

Note: This method is used only if the size of the 2D vector is small. The function creates and returns a copy of the 2D vector. If the vector is large, then copying may degrade performance. In that case, we pass the 2D vector by reference to the function and modify it.

Example,

``````#include<iostream>
#include<vector>
using namespace std;

// the functions modifies vector v into a vector
// of size n X n and all elements
// equals to x
void Return2DVector(vector<vector<int>> &v, int n, int x){

v.clear();

for(int i=0;i<n;++i){

v.push_back(vector<int>());
for(int j=0;j<n;++j){
v[i].push_back(x);
}

}

}

int main()
{
vector<vector<int>> v;
int n,x;

n = 4;
x = 2;
Return2DVector(v, n, x);

for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
cout<<v[i][j]<<' ';
}
cout<<endl;
}

}``````