Loading lessons...
std::vector (quick recap and operations)
std::vector (quick recap and operations)
std::vector is the default go-to container: an array that grows while the program runs. It keeps its elements in a row and remembers its own size.
Create one
#include <vector>
std::vector<int> num = {1, 2, 3};
There is no fixed size to promise up front. The element type and an optional initializer list are all you need.
Add and count
num.push_back(4); // num is now {1, 2, 3, 4}
std::cout << num.size(); // 4
push_back appends at the back. size() tells you how many elements are in the vector right now.
Read an element
num[0] // the first element, fast but unchecked
num.at(1) // the second element, checks the index
at(i) throws an exception if you read out of range; [] does not check at all.
Remove elements
num.erase(num.begin()); // remove the first element
num.erase(num.begin() + 2); // remove the element at index 2
erase needs an iterator so it knows which position to delete. More on iterators soon.
Why is it the default?
- Instant random access by index.
- Cheap to add or remove at the back with
push_backandpop_back. - Knows its size, checks bounds on demand, and grows by itself.
- It is the style choice that keeps most simple code simple.
TL;DR
std::vector<int> num = {1, 2, 3};builds a growable array.num.push_back(4)adds at the back,num.size()counts elements.num[0]is unchecked;num.at(0)checks the index.num.erase(num.begin())removes the first element.vectoris the default container for the growable sequence.