How to Pass Vector to Function in C++: Syntax and Examples
In C++, you can pass a
std::vector to a function by value, by reference, or by constant reference. Passing by constant reference (const std::vector<T>&) is efficient and prevents the function from modifying the vector.Syntax
Here are common ways to pass a std::vector to a function:
- By value: The function gets a copy of the vector.
- By reference: The function can modify the original vector.
- By constant reference: The function can read but not modify the vector, and no copy is made.
cpp
void funcByValue(std::vector<int> v); void funcByReference(std::vector<int>& v); void funcByConstReference(const std::vector<int>& v);
Example
This example shows how to pass a vector by constant reference to print its elements without copying or modifying it.
cpp
#include <iostream> #include <vector> void printVector(const std::vector<int>& vec) { for (int num : vec) { std::cout << num << ' '; } std::cout << '\n'; } int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; printVector(numbers); return 0; }
Output
1 2 3 4 5
Common Pitfalls
Common mistakes when passing vectors to functions include:
- Passing by value unintentionally, which copies the entire vector and can slow down the program.
- Passing by non-const reference when the function should not modify the vector.
- Forgetting to use
constwhen the vector should not be changed, which can lead to bugs.
cpp
/* Wrong: passes vector by value (copy made) */ void process(std::vector<int> v) { // modifies copy, original unchanged v.push_back(10); } /* Right: pass by const reference to avoid copy and prevent modification */ void process(const std::vector<int>& v) { // read-only access for (int x : v) { std::cout << x << ' '; } std::cout << '\n'; }
Quick Reference
Summary tips for passing vectors to functions:
- Use
const std::vector<T>&to pass without copying and prevent changes. - Use
std::vector<T>&if the function needs to modify the vector. - Avoid passing by value unless you need a copy inside the function.
Key Takeaways
Pass vectors by const reference to avoid copying and protect data.
Pass by non-const reference only when you want the function to modify the vector.
Passing by value copies the vector and can reduce performance.
Always use const correctness to make your code safer and clearer.