C++ · Module 6 · Lesson 31 min read

std::vector

Creating vectors (<vector>)

c
std::vector<int> v;                    // empty
std::vector<int> v = { 1, 2, 3 };      // from a list
std::vector<int> v(5);                 // five 0s
std::vector<int> v(5, 7);              // five 7s
std::vector<std::string> names = { "Asha", "Ravi" };

⚠️ std::vector<int> v(5) (five zeros) ≠ std::vector<int> v{5} (one element: 5)

Adding and removing

OperationEffect
v.push_back(x)add to the end
v.emplace_back(args...)construct directly at the end
v.pop_back()remove the last element
v.insert(v.begin() + i, x)insert at position i (slow for big vectors)
v.erase(v.begin() + i)remove at position i
v.clear()remove all
v.resize(n)change the size

Accessing

v[i] (no check), v.at(i) (checked), v.front(), v.back(), v.size(), v.empty()

size vs capacity

  • size(): number of elements
  • capacity(): space allocated
  • When full, vector allocates a bigger block (often 1.5–2×) and moves everything → push_back is fast on average (amortized O(1))
  • v.reserve(n) pre-allocates when you know roughly how many items are coming ✅

Iterator invalidation ⚠️

Adding elements may reallocate: pointers, references and iterators to elements become invalid.

c
int& first = v[0];
v.push_back(99);     // may reallocate
std::cout << first;  // ❌ undefined behaviour

Performance

OperationCost
access v[i]O(1)
push_back / pop_backO(1) amortized
insert/erase in the middleO(n)
search unsortedO(n)

Passing vectors

const std::vector<T>& to read, std::vector<T>& to modify. Return by value (it's moved, not copied).

C++20: std::erase(v, value) and std::erase_if(v, pred)

Remove matching elements in one call.

Example

C++
#include <iostream>
#include <string>
#include <vector>

void print(const std::vector<int>& v) {
    std::cout << "[";
    for (std::size_t i = 0; i < v.size(); ++i) std::cout << (i ? ", " : "") << v[i];
    std::cout << "] size=" << v.size() << '\n';
}

int main() {
    std::vector<int> v;
    for (int i = 1; i <= 5; ++i) v.push_back(i * 10);
    print(v);

    v.insert(v.begin() + 2, 25);        // insert at index 2
    v.erase(v.begin());                 // remove the first element
    v.pop_back();                       // remove the last element
    print(v);

    std::vector<int> five_zeros(5), one_five{5};
    std::cout << "v(5) has " << five_zeros.size() << " elements, v{5} has " << one_five.size() << '\n';

    std::vector<int> expenses = { 500, 0, 1200, 0, 300, 0 };
    std::erase(expenses, 0);                                   // C++20: remove all zeros
    std::erase_if(expenses, [](int x) { return x > 1000; });   // remove large ones
    print(expenses);

    std::vector<int> growth;
    std::size_t last_capacity = 0;
    std::cout << "capacity changes:";
    for (int i = 0; i < 100; ++i) {
        growth.push_back(i);
        if (growth.capacity() != last_capacity) {
            last_capacity = growth.capacity();
            std::cout << ' ' << last_capacity;
        }
    }
    std::cout << '\n';

    std::vector<std::string> names;
    names.reserve(3);                   // avoid reallocations
    names.emplace_back("Asha");
    names.emplace_back(3, 'Z');         // constructs std::string(3, 'Z') in place
    names.push_back("Ravi");
    for (const auto& n : names) std::cout << n << ' ';
    std::cout << "| front=" << names.front() << " back=" << names.back() << '\n';
    return 0;
}

/* Output:
[10, 20, 30, 40, 50] size=5
[20, 25, 30, 40] size=4
v(5) has 5 elements, v{5} has 1
[500, 300] size=2
capacity changes: 1 2 4 8 16 32 64 128
Asha ZZZ Ravi | front=Asha back=Ravi
*/