Step 3 of 6
Insert and erase
Adding or removing elements in the middle of a vector uses iterators: objects that mark a position in a container. You'll study them in depth later; for now:
v.begin()is the position of the first element.v.begin() + iis the position of elementi.v.end()is the position one past the last element.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> steps = {"wake", "coffee", "work"};
steps.insert(steps.begin() + 1, "shower");
steps.insert(steps.end(), "sleep");
steps.erase(steps.begin() + 2);
for (const auto& s : steps) std::cout << s << " ";
std::cout << "(" << steps.size() << ")\n";
}
wake shower work sleep (4)
insert(pos, value)putsvaluebeforepos. Everything after it shifts one place to the right.erase(pos)removes the element atpos. Everything after it shifts left.clear()removes everything.
Cost
Because elements are contiguous, inserting or erasing in the middle must move every element after that position: O(n). Adding or removing at the end is fast (O(1)). If you do lots of middle insertions on big data, a different container may fit better, but for most sizes a vector is still the fastest choice, because moving contiguous memory is very quick.
Validate positions
erase and insert don't check their positions: erasing v.begin() + 10 in a 3-element vector is undefined behavior. When an index comes from outside, check 0 <= i and i < v.size() first (converting carefully between int and the unsigned size()).
Your turn: write void remove_at(std::vector<std::string>& v, int i) that removes element i if it's a valid index and does nothing otherwise.