Sahaj.blogs
19 Dec 2023 · StudyPhase 2 · C++

C++ · STL: vector

std::vector as C++'s list: push_back, size vs capacity, iterators, erase, and reserving memory.

std::vector<T> is the container I’ll use most. It’s a dynamic array, so it’s the closest thing to a Python list, but every element has the same type.

  • push_back / emplace_back add to the end in amortised O(1).
  • size() is how many elements there are. capacity() is how many fit before the next reallocation. When it grows, the vector allocates a bigger block and moves everything over.
  • reserve(n) allocates up front, which avoids repeated reallocations.
  • Iterators (begin(), end()) connect containers to the STL algorithms.
  • Removing elements by value uses the erase–remove idiom.
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;
    std::size_t lastCap = 0;
    for (int i = 0; i < 20; ++i) {
        v.push_back(i);
        if (v.capacity() != lastCap) {
            std::cout << "size " << v.size() << " -> capacity " << v.capacity() << '\n';
            lastCap = v.capacity();
        }
    }

    // remove all even numbers (erase-remove idiom)
    v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end());
    for (int x : v) std::cout << x << ' ';
    std::cout << "\nsize " << v.size() << ", front " << v.front() << ", back " << v.back() << '\n';

    std::vector<double> w;
    w.reserve(1000);
    std::cout << "reserved capacity " << w.capacity() << ", size " << w.size() << '\n';
}

Output:

size 1 -> capacity 1
size 2 -> capacity 2
size 3 -> capacity 4
size 5 -> capacity 8
size 9 -> capacity 16
size 17 -> capacity 32
1 3 5 7 9 11 13 15 17 19 
size 10, front 1, back 19
reserved capacity 1000, size 0

The growth pattern in the output is the library’s choice (here it doubles), not something the standard fixes.

#cpp#stl

Sources

  1. std::vector — cppreference.com
  2. Introduction to std::vector and list constructors — LearnCpp.com
  3. Erase–remove idiom (std::erase, C++20) / std::remove — cppreference.com