In this post, we will see how to return a vector in C++.
vectors can be returned from a function in C++ using two methods: return by value and return by reference. In this article, we will discuss efficient ways to return a vector from a function in C++.
Return by Value
It is a preferred method to return vector from function in C++. It can reduce the execution time and space because in this method, an object is not copied for returning a vector. It only points the pointer to the vector which will be returned.
Code:
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 29 30 |
//Program to return only even elements in a vector #include <vector> #include <iostream> using namespace std; //Print function void print_vector(vector<int> &vect) { cout<<"Even elements are: "; for (auto i = vect.begin(); i != vect.end(); ++i) {cout<< *i << " ";} } //Return by value vector<int> myFunction(vector<int> &results){ vector <int> even_vector; for (const auto &i : results) { if(i%2==0){ even_vector.push_back(i); } } return even_vector; } int main(){ vector<int> vec={20, 51, 11, 88, 44, 77, 14, 99}; vector<int> even_vect=myFunction(vec); print_vector(even_vect); } |
Output:
Further reading:
Return by Reference
This method is better for returning large classes and structures. We will not return the reference of the local variable which is declared in the function because that can lead to dangling reference. In this method, we pass the vector by reference(& myFunction) and we will return as reference only.
Code:
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 |
//Program to calculate the squares of the elements in a vector #include <vector> #include <iostream> using namespace std; //Print function void print_vector(vector<long> &vect) { cout<<"Squares of the elements are: "; for (auto i = vect.begin(); i != vect.end(); ++i) {cout<< *i << " ";} } //Return by reference vector<long> &myFunction(vector<long> &results){ for ( auto &i : results) { i*=i; } return results; } int main(){ vector<long> vec={20, 51, 11, 88, 44, 77, 14, 99}; vector<long> vect=myFunction(vec); print_vector(vect); } |
Output:
Conclusion
In this article we discussed two efficient methods to return vector in C++. We can use return by value for smaller classes or structures. Return by reference method is only useful in the case of large structures and classes.
That’s all about how to return a vector in C++.
Happy Learning!!