8.3 — vector tools
Read one box at a time. No rush.
Handy vector functions#
| Code | What it does |
|---|---|
v.push_back(x) | add x to the end |
v.pop_back() | remove the last item |
v.size() | how many items |
v.empty() | true if there are no items |
v.clear() | remove everything |
v.front() / v.back() | first / last item |
v.at(i) | item at i, with safety check |
v.insert(v.begin() + i, x) | put x at position i |
v.erase(v.begin() + i) | remove the item at i |
C++
std::vector<int> v {};v.push_back(10);v.push_back(20);v.push_back(30); // v is {10, 20, 30} v.erase(v.begin() + 1); // v is {10, 30}v.pop_back(); // v is {10}std::cout << v.size(); // 1Starting with a size#
C++
std::vector<int> zeros(5); // {0, 0, 0, 0, 0}std::vector<int> sevens(3, 7); // {7, 7, 7}Watch out
Note the round brackets. std::vector<int> v(5) makes 5 zeros. But std::vector<int> v{ 5 } makes a list with one item: 5.
Sorting and searching#
The <algorithm> library has ready-made tools:
C++
#include <algorithm> std::vector<int> v { 4, 1, 3 };std::sort(v.begin(), v.end()); // {1, 3, 4}std::reverse(v.begin(), v.end()); // {4, 3, 1}More in 11.2 — The algorithm toolbox.
Tip: press ← / → to move between lessons, / to search.