C/C++ Arena

Step 2 of 6

Loop over a vector

Range-based for works on vectors. Use const auto& to avoid copying each element:

for (const auto& x : v) { ... }
for (auto& x : v) { x *= 2; }     // & to modify in place

Pass vectors to functions by const& (read-only) or & (to modify). Passing by value copies the whole thing.

Your turn: write std::vector<int> running_total(const std::vector<int>& v) that returns the prefix sums. {1, 2, 3, 4} becomes {1, 3, 6, 10}.

Previous: std::vector basics Next: Insert and erase