std::vector

A growable array: push_back, index, pop_back and loop with a range-based for.

C++ · beginner · 7 min · 14 steps · free

What you'll learn

vectors.cpp

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

int main() {
    vector<int> scores = {70, 85};
    scores.push_back(90);          // grows as needed
    scores[0] = 75;
    scores.pop_back();
    size_t count = scores.size();
    int total = 0;
    for (int s : scores) {         // range-based for loop
        total += s;
    }
    cout << count << " " << total << endl;
    return 0;
}

Step by step

  1. A vector with two ints. Its elements live on the heap, managed for you.
  2. push_back adds 90 at the end.
  3. scores changes from [70, 85, 90] to [75, 85, 90].
  4. pop_back removes the last element.
  5. count is created on the stack with the value 2.
  6. total is created on the stack with the value 0.
  7. s is created on the stack with the value 75.
  8. Range-for gives each element in turn.
  9. s changes from 75 to 85.
  10. total changes from 75 to 160.
  11. s goes out of scope and disappears.
  12. It prints 2 160.
  13. The method returns 0.
  14. 2 160.

Common mistakes

Best practices

Key takeaways

Check yourself

v = {1,2}; v.push_back(3); v[2]?

Answer: 3. Added at the end.

Who frees a vector's memory?

Answer: The vector itself. RAII again.

·

More in The Standard Library