C++ Tutorial · Standard Library · Lesson 15 of 21
C++ Vector
std::vector: the default container — add, access, iterate and erase.
std::vector
std::vector is a dynamic array — contiguous, fast and the right default container:
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
std::vector<int> v{5, 3, 9};
v.push_back(1);
v.insert(v.begin(), 7);
std::cout << v.size() << ' ' << v.front() << ' ' << v.back() << ' ' << v[2] << '\n';
v.erase(v.begin() + 1);
std::erase_if(v, [](int n) { return n > 8; }); // C++20
for (int n : v) std::cout << n << ' ';
std::cout << '\n';
try {
v.at(10);
} catch (const std::out_of_range& e) {
std::cout << "out of range\n";
}
}
Output
5 7 1 3 7 3 1 out of range
Run this on your computer — see “Get Started” for setup.
at(i) checks bounds (throws std::out_of_range); [i] doesn't. Call reserve(n) when you know the size in advance to avoid reallocations.
Test yourself
Which vector method checks the index and throws if it's invalid?
operator[]at()get()front()
Show answer
Answer: at()
Practice next
- Two Sum · coding problem
- Product of Array Except Self · coding problem