How to return a vector from a function in C++
In this post, we will learn how to return a vector from a function in C++. You can return a vector from a function simply by declaring the return type of your function as a vector. This task would be very expensive because a copy constructor will be called, which will again be an expensive task, and performance is compromised. However, if we are dealing with small programs we can simply use the return statement.
vector<int> function_name(){ vector<int> vector_name; //perform some tasks (push some elements, sort the vector, remove some elements, etc.) return vector_name; }
Program for returning a vector from a function in C++
C++ program for demonstrating how to return a vector from a function:
#include<iostream> #include<vector> using namespace std; vector<int> function_name(){ vector<int> vector_name; for(int i=0;i<5;i++) vector_name.push_back(i); return vector_name; } int main() { vector<int>v = function_name(); cout << "Printing the vector v from main() " << endl; for(int i=0;i<v.size();i++) cout << v[i] << " " ; cout << endl; return 0; }
Output for the above code
Printing the vector v from main() 0 1 2 3 4
Overcoming the performance issue
While the above implementation works fine for small projects and programs. For bigger programs and projects simply returning the vector will make the program run slow. We can overcome the problem for bigger projects by passing a reference of our vector in the method, this way we won’t have to return it and still have all the modifications done to it.
#include<iostream> #include<vector> using namespace std; void function_name(vector<int> &c){ //adding elements to the vector c.push_back(0); c.push_back(1); c.push_back(2); } int main(){ vector<int> c; function_name(c); cout << "Printing the vector c from main()" << endl; for(int i=0;i<c.size();i++) cout << c[i] << " " ; return 0; }
Output for the above code
Printing the vector c from main() 0 1 2
Leave a Reply