C++ std::vector::insert
Insert a group of new stops before a known position on a route.
A simple example
std::vector::insert
- Start with A, C
- Do this Insert B between them
- Result A, B, C
Syntax
stops.insert(position, extraStops)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonInsert two pickup stops before the depot
A shuttle normally travels straight from the school to the depot. The dispatcher adds two afternoon pickups and needs them to appear in the supplied order before the final stop.
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> stops{"School", "Depot"};
stops.insert(stops.begin() + 1, {"Hall", "Pool"});
for (std::size_t i = 0; i < stops.size(); ++i) {
std::cout << (i ? ", " : "") << stops[i];
}
return 0;
}
School, Hall, Pool, Depot
Hall and Pool are inserted between the school and the depot in pickup order.
Extend a reading list
A class has chosen one novel and adds two more titles. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.
Update an equipment checklist
A technician adds the final item after packing two pieces of equipment. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.
What to watch for
Inserting into a vector can invalidate iterators and references. Obtain positions again after insertion.