How to return a vector in C++
In this tutorial, we will discuss how to return a vector in C++. There are 2 ways to return a vector in C++ i.e. by value and by reference. We will see which one is more efficient and why.
Return by Value
This is the preferred method in C++ 11, because we have an optimization in C++ 11 Compiler, it’s called Name Return Value Optimization (NRVO). In this method, the compiler optimizes so that function doesn’t get constructed twice. In this method an object is not copied for returning a vector, it will point the pointer to the new vector which will be returned not causing extra time and space.
Code
#include <bits/stdc++.h> using namespace std; vector<int> divVecByVal(vector<int> &v){ vector<int> res(v.size()); for(int i=0; i<v.size(); i++) res[i] = v[i]/10; return res; } int main(){ vector<int> v = {10, 20, 30, 40, 50}; cout << "Original Vector: "; for(auto a:v) cout << a << " "; cout << endl; vector<int> v2 = divVecByVal(v); cout << "Resultant vector: "; for(auto a:v2) cout << a << " "; cout << endl; return 0; }
Output
Original Vector: 10 20 30 40 50 Vector after calling function: 1 2 3 4 5
Also read: How to return a vector from a function in C++
Return by Reference
In this method, we just return the reference of the vector. And one more thing we must remember is to not return the reference of local variable declared in the function, if one tries to do then he will have a dangling reference (a reference to a deleted object).
Code
#include <bits/stdc++.h> using namespace std; vector<int> &divVecByRef(vector<int> &v){ for(int i=0; i<v.size(); i++) v[i] /= 10; return v; } int main(){ vector<int> v = {10, 20, 30, 40, 50}; cout << "Original Vector: "; for(auto a:v) cout << a << " "; cout << endl; vector<int> v2 = divVecByRef(v); cout << " Resultant vector: "; for(auto a:v2) cout << a << " "; cout << endl; return 0; }
Output
Original Vector: 10 20 30 40 50 Vector after calling function: 1 2 3 4 5
Note: If you try to return the local variable, you will end up with the below error, so never return the local variable.
Output
warning: reference to stack memory associated with local variable 'res' returned [-Wreturn-stack-address] zsh: segmentation fault ./a.out
Leave a Reply