STL Vector

STL Vector in C++: A raw array is a shelf bolted to the wall with exactly ten slots. Fill it and you are stuck: no eleventh book fits, and if you only ever…

The Analogy: A Shelf That Builds Its Own Extensions

A raw array is a shelf bolted to the wall with exactly ten slots. Fill it and you are stuck: no eleventh book fits, and if you only ever store three, seven slots sit empty forever.

A std::vector is a shelf with a builder on retainer. Put books on it and it takes them. Reach the end of the current shelf and the builder quietly puts up a longer one, moves every book across, and takes the old one down — you never asked, you never noticed, and the books are still in order. Ask how many books there are and it knows. Ask it to forget the last three and they are gone, along with the space they used.

That is the whole pitch: a vector is an array that manages its own size and its own memory. It stores its elements in one contiguous block, exactly like an array, so indexing is just as fast and the CPU cache is just as happy. What it adds is the bookkeeping you would otherwise write by hand with new, delete and a count variable you must never forget to update.

In modern C++, std::vector is the default container. Reach for something else only when you have a specific reason.


Syntax or Core Structure

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

int main() {
    std::vector<int> empty;                       // size 0
    std::vector<int> scores{90, 75, 88};          // three elements
    std::vector<int> zeros(5);                    // five ints, all 0
    std::vector<int> fives(4, 5);                 // 5, 5, 5, 5
    std::vector<std::string> names{"Ada", "Grace"};

    // Growing
    scores.push_back(100);                        // 90, 75, 88, 100
    names.emplace_back("Alan");                   // constructs in place

    // Reading
    std::cout << "first: " << scores.front() << "\n";
    std::cout << "last:  " << scores.back() << "\n";
    std::cout << "third: " << scores[2] << "\n";
    std::cout << "count: " << scores.size() << "\n";
    std::cout << "empty? " << (scores.empty() ? "yes" : "no") << "\n";

    // Modifying
    scores[0] = 95;
    scores.at(1) = 80;                            // bounds-checked
    scores.pop_back();                            // removes the 100

    // Iterating -- reference avoids a copy, const says "read only"
    int total = 0;
    for (const int& s : scores) {
        total += s;
    }
    std::cout << "total: " << total << "\n";

    // Index form, when you need the position
    for (std::size_t i = 0; i < scores.size(); ++i) {
        std::cout << i << ": " << scores[i] << "\n";
    }

    // Emptying
    scores.clear();                               // size 0, capacity unchanged
    std::cout << "after clear: " << scores.size() << "\n";
}

Note std::size_t for the loop counter, not int: size() returns an unsigned type, and comparing a signed int against it produces a warning (and, with a very large vector, a wrong answer).


Technical Depth: Size, Capacity and Iterators

The two numbers every vector carries

Size is how many elements you have. Capacity is how many it could hold before it must move to a bigger block. They are not the same, and confusing them causes real bugs.

std::vector<int> v;
for (int i = 0; i < 10; ++i) {
    v.push_back(i);
    std::cout << "size " << v.size() << ", capacity " << v.capacity() << "\n";
}

Typical output shows capacity jumping 1, 2, 4, 8, 16 — it roughly doubles, so push_back is cheap on average even though the occasional call has to reallocate. That growth pattern is what makes appending to a vector amortised constant time.

If you know roughly how many elements are coming, say so:

std::vector<int> v;
v.reserve(1000);        // one allocation, capacity 1000, size still 0

reserve changes capacity only. resize changes size — v.resize(5) gives you five real, value-initialised elements you can index immediately.

CallChanges sizeChanges capacityElements exist afterwards
reserve(n)NoGrows to at least nNo
resize(n)Yes, to nGrows if neededYes, n of them
clear()To 0NoNo
shrink_to_fit()NoDown to sizeUnchanged

A common mistake is v.reserve(10); v[0] = 5; — capacity 10, size 0, so v[0] is undefined behaviour. Use resize if you want to index, reserve if you want to push_back.

Reallocation invalidates everything pointing in

When a vector grows past its capacity it allocates a new block and moves the elements. Every pointer, reference and iterator into the old block becomes dangling:

std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4);              // may reallocate
// std::cout << first;       // DANGLING -- undefined behaviour

The rule: do not hold a reference into a vector across any operation that can change its size. This is also why you must never push_back to a vector you are iterating with a range-based for.

[] versus at()

std::vector<int> v{1, 2, 3};
v[10];        // undefined behaviour -- no check, possibly no crash
v.at(10);     // throws std::out_of_range
operator[]at()
Bounds checkedNoYes
On bad indexUndefined behaviourThrows std::out_of_range
CostZeroOne comparison
Use whenIndex provably validIndex comes from outside

Use at() for anything derived from user input or a file; [] inside a loop you control.

Iterators and <algorithm>

begin() points at the first element, end() one past the last. That half-open range is what the standard algorithms consume:

#include <algorithm>
#include <numeric>

std::vector<int> v{5, 3, 9, 1};

std::sort(v.begin(), v.end());                            // 1, 3, 5, 9
int sum = std::accumulate(v.begin(), v.end(), 0);         // 18
auto it = std::find(v.begin(), v.end(), 9);
if (it != v.end()) std::cout << "found at " << (it - v.begin()) << "\n";

auto big = std::count_if(v.begin(), v.end(), [](int n) { return n > 3; });
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });   // descending

Removing elements

v.pop_back();                                  // last element, cheap
v.erase(v.begin() + 2);                        // index 2, shifts the rest
v.erase(v.begin() + 1, v.begin() + 4);         // a range
v.insert(v.begin(), 0);                        // front insert, shifts everything

Erasing from the middle is O(n) because everything after it slides down. To remove every element matching a condition, use erase-remove rather than a loop:

v.erase(std::remove_if(v.begin(), v.end(),
                       [](int n) { return n < 0; }),
        v.end());

std::remove_if shuffles the survivors to the front and returns the new logical end; erase then drops the tail. One pass instead of n shifts. In C++20 this is simply std::erase_if(v, pred);.

Deleting inside a plain loop is the classic trap:

for (std::size_t i = 0; i < v.size(); ++i) {
    if (v[i] < 0) v.erase(v.begin() + i);      // BUG: skips the next element
}

After erasing at i, the next element is now at i, but ++i moves past it. Either use erase-remove, or do not increment when you erase.

Vectors of objects, and vectors in functions

void print(const std::vector<int>& v);         // read only, no copy
void fill(std::vector<int>& v);                // will modify the caller's
std::vector<int> make();                       // return by value, cheap (moved)

Passing by value copies every element. Return by value freely, though — the compiler moves rather than copies.

emplace_back constructs the element directly inside the vector; push_back constructs it and then moves it in. For a struct with several fields, orders.emplace_back("Ada", 3, 4.99) avoids one temporary.

std::vector<bool> is not a vector

It is a bit-packed specialisation that does not store real bool objects, so bool& b = flags[0]; will not compile. If you need a real container of booleans, use std::vector<char> or std::deque<bool>.

Choosing a container

NeedContainer
Indexed access, append at the endstd::vector
Fixed size known at compile timestd::array
Frequent insert/erase at both endsstd::deque
Frequent insert/erase in the middlestd::list
Key to value lookupstd::map / std::unordered_map

Even for middle insertions, a vector often beats a list in practice because contiguous memory is so much friendlier to the cache. Measure before switching.


Real World Example: A Race Results Board

Race timing is a good fit for a vector: entrants arrive in an unknown order, the list grows as they finish, and afterwards you want it sorted, filtered and summarised. Everything below is one contiguous block of memory being reshaped.

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <optional>
#include <sstream>
#include <string>
#include <vector>

struct Finisher {
    std::string name;
    std::string category;
    double seconds = 0.0;
};

std::string formatTime(double seconds) {
    int mins = static_cast<int>(seconds) / 60;
    double rest = seconds - mins * 60;
    std::ostringstream out;
    out << mins << ":" << std::setw(5) << std::setfill('0')
        << std::fixed << std::setprecision(2) << rest;
    return out.str();
}

double fastest(const std::vector<Finisher>& results) {
    if (results.empty()) return 0.0;
    auto it = std::min_element(results.begin(), results.end(),
                               [](const Finisher& a, const Finisher& b) {
                                   return a.seconds < b.seconds;
                               });
    return it->seconds;
}

double averageTime(const std::vector<Finisher>& results) {
    if (results.empty()) return 0.0;
    double total = std::accumulate(results.begin(), results.end(), 0.0,
                                   [](double sum, const Finisher& f) {
                                       return sum + f.seconds;
                                   });
    return total / results.size();
}

std::vector<Finisher> inCategory(const std::vector<Finisher>& results,
                                 const std::string& category) {
    std::vector<Finisher> out;
    out.reserve(results.size());
    std::copy_if(results.begin(), results.end(), std::back_inserter(out),
                 [&category](const Finisher& f) { return f.category == category; });
    return out;
}

std::optional<std::size_t> placeOf(const std::vector<Finisher>& sorted,
                                   const std::string& name) {
    for (std::size_t i = 0; i < sorted.size(); ++i) {
        if (sorted[i].name == name) return i + 1;
    }
    return std::nullopt;
}

void printBoard(const std::vector<Finisher>& sorted) {
    std::cout << std::left << std::setw(4) << "#"
              << std::setw(10) << "Name"
              << std::setw(9) << "Cat"
              << "Time\n";
    std::cout << std::string(31, '-') << "\n";
    for (std::size_t i = 0; i < sorted.size(); ++i) {
        std::cout << std::left << std::setw(4) << (i + 1)
                  << std::setw(10) << sorted[i].name
                  << std::setw(9) << sorted[i].category
                  << formatTime(sorted[i].seconds) << "\n";
    }
}

int main() {
    std::vector<Finisher> results;
    results.reserve(8);                            // we expect about eight

    results.emplace_back("Ada",   "senior", 1512.40);
    results.emplace_back("Grace", "senior", 1488.15);
    results.emplace_back("Alan",  "junior", 1602.90);
    results.emplace_back("Edsger","senior", 1745.05);
    results.emplace_back("Barbara","junior", 1533.75);
    results.emplace_back("Ken",   "veteran", 1901.20);

    // A late disqualification -- remove by predicate, not by index loop.
    results.erase(std::remove_if(results.begin(), results.end(),
                                 [](const Finisher& f) { return f.name == "Edsger"; }),
                  results.end());

    std::sort(results.begin(), results.end(),
              [](const Finisher& a, const Finisher& b) { return a.seconds < b.seconds; });

    printBoard(results);

    std::cout << "\nfinishers: " << results.size()
              << "  (capacity " << results.capacity() << ")\n";
    std::cout << "winner:    " << results.front().name << "\n";
    std::cout << "last:      " << results.back().name << "\n";
    std::cout << "fastest:   " << formatTime(fastest(results)) << "\n";
    std::cout << "average:   " << formatTime(averageTime(results)) << "\n";

    std::vector<Finisher> juniors = inCategory(results, "junior");
    std::cout << "juniors:   " << juniors.size() << "\n";
    for (const Finisher& f : juniors) {
        std::cout << "  " << f.name << " " << formatTime(f.seconds) << "\n";
    }

    if (auto place = placeOf(results, "Alan")) {
        std::cout << "Alan finished " << *place << "\n";
    } else {
        std::cout << "Alan did not finish\n";
    }
}

Output:

#   Name      Cat      Time
-------------------------------
1   Grace     senior   24:48.15
2   Ada       senior   25:12.40
3   Barbara   junior   25:33.75
4   Alan      junior   26:42.90
5   Ken       veteran  31:41.20

finishers: 5  (capacity 8)
winner:    Grace
last:      Ken
fastest:   24:48.15
average:   26:47.68
juniors:   2
  Barbara 25:33.75
  Alan 26:42.90
Alan finished 4

Every design choice here is a vector idiom. reserve(8) up front means the six emplace_back calls cause exactly one allocation instead of four; note the final capacity is still 8 even though size is 5, because erasing never shrinks capacity. emplace_back builds each Finisher directly in the vector's memory rather than constructing a temporary and moving it. The disqualification uses erase-remove rather than a loop with erase(begin() + i) — that loop is where the skipped-element bug lives, and erase-remove is one pass regardless.

Every function that only reads takes const std::vector<Finisher>&, so nothing copies six structs to answer a question; inCategory returns by value because it genuinely produces a new collection, and that return is moved, not copied. Inside it, reserve(results.size()) sizes the worst case once so back_inserter never reallocates. fastest uses std::min_element with a comparator instead of a hand-written loop, and averageTime uses std::accumulate with a 0.0 seed — pass 0 there instead and the whole accumulation happens in int, silently truncating every time. placeOf returns std::optional<std::size_t> because "not in the list" is a normal answer and there is no sensible integer to mean it; note it returns i + 1, since positions are 1-based for humans and 0-based for the vector. And printBoard iterates with an index precisely because it needs that position — where the other loops, which do not, use const Finisher& range-based for and avoid copying a struct per iteration.

Sorting deserves one note: it reorders the vector in place, so any reference or iterator you were holding into it now points at a different runner. That is fine here because nothing is held across the sort call, and it is exactly the discipline vectors demand.


Common Mistakes

  1. Indexing past the end. v[v.size()] is undefined behaviour, not an error. There is no element there.
  2. Confusing reserve with resize. reserve(10) leaves size at 0, so v[0] = x is invalid. Use resize if you want to index.
  3. Holding a reference across a push_back. Reallocation moves the elements and your reference dangles.
  4. Modifying a vector while range-iterating it. for (int x : v) v.push_back(x); invalidates the loop's own iterators.
  5. Erasing in an index loop without adjusting the index. Erasing at i then doing ++i skips one element. Use erase-remove.
  6. Passing by value. void f(std::vector<int> v) copies every element. Take const&.
  7. int i against size(). Signed/unsigned comparison warning, and wrong for very large vectors. Use std::size_t.
  8. Expecting clear() to free memory. It sets size to 0 and leaves capacity alone. Use shrink_to_fit(), or swap with an empty vector.
  9. Seeding accumulate with 0 for doubles. The sum is computed in int. Write 0.0.
  10. Assuming std::vector<bool> behaves like the others. It is bit-packed; you cannot take a reference to an element.

Best Practices

  • Make std::vector your default container. Contiguous memory, no manual new/delete, cache-friendly.
  • reserve when you know the count. One allocation instead of a run of doublings.
  • emplace_back for objects, push_back for scalars. It skips a temporary.
  • at() for untrusted indices, [] for indices you control.
  • Use <algorithm> instead of hand-written loops. sort, find, count_if, accumulate, min_element, remove_if are all clearer and better optimised.
  • Take const std::vector<T>& to read, std::vector<T>& to modify, and return by value.
  • Range-based for with const T& unless you need the index.
  • Prefer std::erase_if(v, pred) in C++20, erase-remove before it.
  • Never resize a vector you are iterating.

Practice Exercises

  1. Build a std::vector<double> of temperature readings from user input (stop on a sentinel value). Print the count, minimum, maximum and mean using <algorithm> and <numeric> rather than manual loops.
  2. Write std::vector<int> evensOnly(const std::vector<int>& in) two ways: once by push_back in a loop, once with std::copy_if and std::back_inserter. Confirm they agree.
  3. Print size() and capacity() after each of twenty push_back calls. Describe the growth pattern, then repeat with a reserve(20) first and explain the difference.
  4. Write a function that removes every duplicate from a sorted std::vector<int> using std::unique plus erase. Then explain why std::unique alone does not change the vector's size.