# C++ Notes: Passing Vector Parameters

## Vectors as parameters

To avoid making a copy of the entire vector, always pass vectors as reference parameters.

- It is much faster. Not only are references only 4 bytes long, but copying a vector means dynamically allocating new memory for a new vector, copying all elements, and then deallocating this memory when the function returns.
- If the function needs to change the elements of a vector, it's necessary to pass the vector by reference so that the changes are made to the original, not a temporary copy.
- If you are not changing the values in the vector, declare it `const`.

## Example -- Function to add numbers in an vector

This main program calls a function which returns the sum of all elements in an vector and uses the returned value to compute the average.

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
    // vector/vector-average.cpp - Averages numbers in vector
    // Fred Swartz - 2003-11-20

    #include <vector>
    #include <iostream>
    using namespace std;

    float sum(const vector<float>& x); // prototype

    //====================================================== main
    int main() {
        vector<float> a;   // Declare a vector.

        float temp;
        while (cin >> temp) {
            a.push_back(temp);
        }

        cout << "Average = " << sum(a)/a.size() << endl;

        return 0;
    }

    //======================================================= sum
    // sum adds the values of the vector it is passed.
    float sum(const vector<float>& x) {
        float total = 0.0;  // the sum is accumulated here
        for (int i=0; i<x.size(); i++) {
            total = total + x[i];
        }
        return total;
    }

## Comparison of vector and array parameters

In addition to protecting against buffer overflow by automatically expanding as necessary, vectors keep track of the number of elements in them. See Passing Arrays as Parameters to constrast these approaches for this same problem.