TL ; DR:
insert(v.begin() + i, x) puts x at index i. Use erase(v.begin() + i) to take out the item at index i. The other items move to make room or to close the gap.
vector<string> colors = {"red", "green", "blue"};
colors.insert(colors.begin() + 1, "pink");
// colors is now {"red", "pink", "green", "blue"}
colors.erase(colors.begin());
// colors is now {"pink", "green", "blue"}
Full lesson:
push_back adds an item at the end, and pop_back takes the last one away. To work anywhere else in a vector, you need a position.
v.begin() is the position of the first item. Then v.begin() + i is the position of index i. Both insert and erase take such a position, not a plain index.
insert(pos, x) puts x at that position. The items from there on move one place to the right:
vector<string> pets = {"Rex", "Milo"};
pets.insert(pets.begin(), "Luna");
// pets is now {"Luna", "Rex", "Milo"}
erase(pos) takes out the item at that position. The items after it move one place to the left:
pets.erase(pets.begin() + 1);
// pets is now {"Luna", "Milo"}
Watch the indexes. After an insert or a removal, the items behind that spot have new indexes.
C++ doesn't check the position for you. A position past the end can crash the program.
Your task
pets holds the pets waiting at the vet, in order.
Bella has an appointment, so she goes second, at index 1. Then Milo goes home. Take him out of the line.
The code below prints how many pets wait once Bella is in. At the end, it prints the pets left.
Expected output:
4
Rex Bella LunaFree plan: 30 tutor messages. PRO is unlimited.
