C++ by Example
C++ by Example

Vectors

2 min read

Vectors

std::vector<T> is a dynamically sized array that grows automatically. It is the right default container for most sequences in C++.

Creating and filling a vector

#include <iostream>
#include <vector>

int main() {
    std::vector<int> a = {1, 2, 3, 4, 5};   // initializer list
    std::vector<int> b(10, 0);               // 10 zeros
    std::vector<int> c;                      // empty

    c.push_back(10);
    c.push_back(20);
    c.push_back(30);

    std::cout << c.size() << "\n";   // 3
}

Accessing elements

std::vector<std::string> words = {"alpha", "beta", "gamma"};

std::cout << words[0]      << "\n";   // alpha  — no bounds check
std::cout << words.at(1)   << "\n";   // beta   — throws if out of range
std::cout << words.front() << "\n";   // alpha
std::cout << words.back()  << "\n";   // gamma

Common operations

#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5};

    v.push_back(9);          // append
    v.pop_back();            // remove last

    v.insert(v.begin(), 0);  // insert 0 at front
    v.erase(v.begin() + 2);  // remove element at index 2

    std::cout << v.size()     << "\n";   // number of elements
    std::cout << v.capacity() << "\n";   // allocated storage

    v.clear();
    std::cout << v.empty() << "\n";      // 1 (true)
}

Capacity vs. size

size() is the number of elements. capacity() is the allocated storage. When push_back exceeds capacity, the vector reallocates — typically doubling — and copies all elements. If you know the final size, reserve() avoids repeated reallocations:

std::vector<int> v;
v.reserve(1000);   // allocate space for 1000 without setting size

for (int i = 0; i < 1000; i++) v.push_back(i);

Iterating

std::vector<int> v = {10, 20, 30, 40};

// Range-based for (preferred)
for (int n : v) std::cout << n << " ";

// Index-based
for (size_t i = 0; i < v.size(); i++) std::cout << v[i] << " ";

// Iterator
for (auto it = v.begin(); it != v.end(); ++it) std::cout << *it << " ";

Vectors of objects

Vectors work with any copyable or movable type:

#include <string>
#include <vector>
#include <iostream>

struct Person {
    std::string name;
    int age;
};

int main() {
    std::vector<Person> people;
    people.push_back({"Alice", 30});
    people.push_back({"Bob",   25});
    people.emplace_back("Carol", 35);   // construct in-place, no copy

    for (const auto& p : people) {
        std::cout << p.name << ": " << p.age << "\n";
    }
}

emplace_back constructs the object directly inside the vector, avoiding an extra copy or move compared to push_back.

2D vectors

std::vector<std::vector<int>> grid(3, std::vector<int>(4, 0));  // 3×4 grid of zeros

grid[1][2] = 7;
std::cout << grid[1][2] << "\n";   // 7
C++ by Example
C++ by Example

Learn modern C++ through working code. Each chapter introduces one concept — variables, functions, classes, templates, smart pointers, concurrency — with a clear example, a line-by-line explanation, and notes on how it applies in real programs.

View book →