How to Return Vector from Function in C++: Simple Guide
In C++, you can return a
std::vector from a function by specifying std::vector<Type> as the return type. Simply create and fill the vector inside the function, then return it by value.Syntax
To return a vector from a function, declare the function's return type as std::vector<Type>. Inside the function, create a vector, add elements, and return it.
- std::vector<Type>: The vector type with the element type inside <>.
- functionName(): Your function's name.
- return vectorVariable;: Returns the vector by value.
cpp
std::vector<int> functionName() { std::vector<int> vec; // add elements to vec return vec; }
Example
This example shows a function that creates a vector of integers, fills it with numbers 1 to 5, and returns it. The main function then prints the returned vector.
cpp
#include <iostream> #include <vector> std::vector<int> createVector() { std::vector<int> numbers; for (int i = 1; i <= 5; ++i) { numbers.push_back(i); } return numbers; } int main() { std::vector<int> myVector = createVector(); for (int num : myVector) { std::cout << num << " "; } std::cout << std::endl; return 0; }
Output
1 2 3 4 5
Common Pitfalls
One common mistake is returning a reference to a local vector, which becomes invalid after the function ends. Always return by value or use pointers/smart pointers if needed.
Another issue is forgetting to include the <vector> header or using the wrong namespace.
cpp
// Wrong: returning reference to local vector (dangerous) std::vector<int>& wrongFunction() { std::vector<int> localVec = {1, 2, 3}; return localVec; // localVec is destroyed after function ends } // Correct: return by value std::vector<int> correctFunction() { std::vector<int> localVec = {1, 2, 3}; return localVec; // safe to return by value }
Quick Reference
- Use
std::vector<Type>as return type. - Return vector by value to avoid dangling references.
- Include
<vector>and usestd::vector. - Fill vector inside function before returning.
Key Takeaways
Always declare the function return type as std::vector with the correct element type.
Return vectors by value to ensure safe copying and avoid invalid references.
Include the header and use the std namespace or prefix.
Do not return references to local vectors as they get destroyed after function ends.
Fill the vector inside the function before returning it.