Modifying vector Elements in Loops

Contents

Modifying vector Elements in Loops#

We’ve been looping over elements of a vector like this:

std::vector<double> vec{1.0, 2.0, 3.0, 4.0};

for (auto e : vec) {
    // do something with e
}

Here, in the body of the loop (between the { }) we have access to a copy of the current element of the vector vec (through e). We cannot modify the contents of vec using e, because e is a copy of the current element.

If we want to modify what is actually stored in vec, then we need to access a reference to the current element in vec. We can do this as:

std::vector<double> vec{1.0, 2.0, 3.0, 4.0};

for (auto &e : vec) {
    // do something with e
}

Now e is a reference to the element in vec, and if we modify e, then the contents of vec reflect that change.

Example#

Here’s an example showing different ways of accessing elements of a vector and whether we can modify them:

Listing 42 vector_modify.cpp#
#include <iostream>
#include <vector>

int main() {

    std::vector<double> container(10, 0.0);

    // here "e" is just a double that is initialized via a copy to the
    // current element of container.  Since it is not a reference, it
    // is disconnected completely from container.

    for (auto e : container) {
        e = 1.0;
    }

    std::cout << "current vector: ";
    for (auto e : container) {
        std::cout << e << " ";
    }
    std::cout << std::endl;

    // now we create a reference (double&) to the current element in
    // the container.  This means that "e" is sharing the exact memory
    // in the vector as the current element, so if we modify it,
    // container is modified too.

    for (auto& e : container) {
        e = 2.0;
    }

    std::cout << "current vector: ";
    for (auto e : container) {
        std::cout << e << " ";
    }
    std::cout << std::endl;

}