Lesson 215 +5 XP

<vector> Reference

<vector> Reference

A std::vector is a growable array: like an array but with the ability to change length. This is the reference sheet for its most useful member functions.

Overview

#include <vector>
#include <iostream>

using namespace std;

int main() {
    vector<int> scores;
    scores.push_back(42);
    cout << scores[0];   // 42
}

The vector is generic - `vector<> of any type, including your own classes and nested vectors.

Adding and removing elements

FunctionWhat it doesResult
push_back(x)adds x at the backsize grows by 1
pop_back()removes last elementsize shrinks by 1
insert(iter, x)inserts x at the iterator positionshifts the rest right
erase(iter)removes the element at the iteratorshifts the rest left
clear()removes everythingsize becomes 0

insert and erase make the existing elements shift - that's O(n). Use them when you need to, but push/pop is cheap.

Adding by iterators

Iterators are vector's "pointer-like" locators:

vector<int> v = {10, 20, 40};
v.insert(v.begin() + 2, 30);   // {10, 20, 30, 40}
v.erase(v.begin());            // {20, 30, 40}

Size and capacity

FunctionWhat it returnsNotes
size()number of usable elementswhat you want for loops
capacity()memory slots allocatedmay be > size
empty()bool - is size 0?prefers to size() == 0

capacity is the internal storage room; size is the filled half. The vector auto-grows as you push.

Preparing for growth

FunctionWhat it does
reserve(n)pre-allocate room for at least n elements (doesn't change size)
resize(n)set size to n; adds default elements or trims
  • reserve reduces reallocations when you know the size.
  • resize actually changes size().

Accessing elements

FunctionExampleNotes
at(i)v.at(2)bounds-checked - on out-of-range it throws
operator[]v[2]no checks - faster, you're on your own
front()v.front()first element
back()v.back()last element
data()v.data()pointer to the first element's raw memory

Iterators and range-for

begin() and end() locate the run:

for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
    cout << *it;
}

Since C++11 you can skip iterators entirely with a range-for:

for (int x : v) {
    cout << x;
}

cbegin()/:`cend() exist for const views. A range-for over a vector is sugar for the iterator loop.

Notes

  • A vector's elements live in one contiguous block of memory - that's why it's fast to index.
  • push_back/pop_back operate at the end in neighbor O(1) time.
  • insert/erase in the middle shuffle elements and cost O(n).insert usually triggers reallocation if there's not room.
  • Reallocation invalidates iterators and references - invalid meaning "do not use the old ones".
  • at throws std::out_of_range; [] trusts you to stay in sat-of-bounds.

TL;DR

  • Add to end: push_back / pop_back.
  • Size and capacity: size() / capacity() / empty() / resize() / reserve() / clear().
  • Read: at() (checked) / [] (fast) / front() / back() / data().
  • Just loop: range-for over const-like iterators:

for (int x : v).