. Advertisement .
..3..
. Advertisement .
..4..
In today’s tutorial, we will introduce to you thoroughly how to return a vector C++. Wait for no more but dig in for further helpful details!
How To Return A Vector C++?
There are two different methods to return a vector in C++ programme. Each has its own pros and cons. Scroll down to know what they are and how they can be of efficiency!
Method #1: Employ the vector<T> &func() Notation
This method utilizes the return by reference approach, which is ideal for returning big classes and structs.
There is only one minor notice in such a technique: You may not want to return the local variable declared in the function itself since doing so may result in a dangling reference.
The arr vector is passed by reference in the example below, and it is also returned as a reference.
Running the code:
#include <iostream>
#include <vector>
#include <iterator>
using std::cout; using std::endl;
using std::vector;
vector<int> &multiplyByFive(vector<int> &arr)
{
for (auto &i : arr) {
i *= 3;
}
return arr;
}
int main() {
vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
vector<int> arrby3;
cout << "arr - | ";
copy(arr.begin(), arr.end(),
std::ostream_iterator<int>(cout," | "));
cout << endl;
arrby3 = multiplyByFive(arr);
cout << "arrby3 - | ";
copy(arrby3.begin(), arrby3.end(),
std::ostream_iterator<int>(cout," | "));
cout << endl;
return EXIT_SUCCESS;
}
Output:
arr - | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
arrby3 - | 3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 10 |
Method #2: Employ the vector<T> func() Notation
If we want to return a vector variable that was declared in the function, the return by value approach is the best recommendation.
At that point, this method’s move-semantics are what give it its effectiveness. It prevents the object from being copied when a vector is returned, saving time and space.
It really directs the reference to the returned vector object, which speeds up program execution compared to copying the entire structure or class.
The coding below is our explanation for this troubleshooting.
Running the code:
#include <iostream>
#include <vector>
#include <iterator>
using std::cout; using std::endl;
using std::vector;
vector<int> multiplyByFour(vector<int> &arr)
{
vector<int> mult;
mult.reserve(arr.size());
for (const auto &i : arr) {
mult.push_back(i * 6);
}
return mult;
}
int main() {
vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
vector<int> arrby6;
arrby6 = multiplyByFour(arr);
cout << "arr - | ";
copy(arr.begin(), arr.end(),
std::ostream_iterator<int>(cout," | "));
cout << endl;
cout << "arrby6 - | ";
copy(arrby6.begin(), arrby6.end(),
std::ostream_iterator<int>(cout," | "));
cout << endl;
return EXIT_SUCCESS;
}
Output:
arr - | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
arrby6 - | 6 | 12 | 18 | 24 |30 | 36 | 42 | 48 | 54 | 60 |
Conclusion
You must have grasped detailedly how to return a vector C++ by now. Hopefully, this article can be handy for your coding. See then!
Leave a comment