In this article, we are going to learn how to return a vector from a function. A vector contains many values ,so returning a vector will return a chunk of values that this vector holds. We will learn doing this by different techniques.
Using call by value to Return Vector From a Function
In this example, we are going to see how to get a vector returned from a function by using the call by value and get return value from the function as a vector. Here we are passing a vector to a function and also the value that we want to use inside this function. This value will get multiplied to each element of the vector and this modified vector is returned by this function as return value.
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
vector<int> ModifytheVectorbyVal(vector<int> &vec,int Val)
{
vector<int> newvec;
newvec.reserve(vec.size());
for (const auto &i : vec) {
newvec.push_back(i * Val);
}
return newvec;
}
int main()
{
vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
cout <<"Vector Elements are :";
for (size_t i = 0; i < vec.size(); ++i)
{
cout << vec[i] << " ";
}
int Val;
cout <<"\nPlease enter the multiplier :";
cin >> Val;
vector<int> Modifiedvec;
Modifiedvec = ModifytheVectorbyVal(vec,Val);
cout << endl;
cout <<"Modified Vector Elements are :";
for (size_t i = 0; i < Modifiedvec.size(); ++i) {
cout << Modifiedvec[i] << " ";
}
cout << endl;
return 0;
}
Output:
Vector Elements are :1 2 3 4 5 6 7 8 9 10
Please enter the multiplier :5
Modified Vector Elements are :5 10 15 20 25 30 35 40 45 50
Using call by reference to Return Vector From a Function
In this example, we are going to see how to get a vector returned from a function by using the
call by reference from the function as a vector.
Here we are passing a vector to a function as a reference and also the value that we want to use inside this function. This value will get multiplied to each element of the vector and this passed vector gets the changes reflected in the original passed vector.
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
vector<int> &ModifytheVectorbyVal(vector<int> &vec,int Val)
{
for (auto &iter : vec) {
iter *= Val;
}
return vec;
}
int main()
{
vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
cout <<"Vector Elements are :";
for (size_t i = 0; i < vec.size(); ++i)
{
cout << vec[i] << " ";
}
int Val;
cout <<"\nPlease enter the multiplier :";
cin >> Val;
vector<int> Modifiedvec;
Modifiedvec = ModifytheVectorbyVal(vec,Val);
cout << endl;
cout <<"Modified Vector Elements are :";
for (size_t i = 0; i < Modifiedvec.size(); ++i) {
cout << Modifiedvec[i] << " ";
}
cout << endl;
return 0;
}
Output:
Vector Elements are :1 2 3 4 5 6 7 8 9 10
Please enter the multiplier :5
Modified Vector Elements are :5 10 15 20 25 30 35 40 45 50