C++ vector::push_back
Append a new passenger to the end of a school bus register.
A simple example
vector::push_back
- Start with List containing A
- Do this Append B
- Result A, B
Syntax
riders.push_back(name)
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
./lessonAdd the last student to the bus register
Two families have already booked seats on a school bus. A third student registers at the desk, so the coordinator appends the name and checks the final passenger count before departure.
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> riders{"Mira", "Sam"};
riders.push_back("Nia");
std::cout << riders.size();
return 0;
}
3
The two earlier bookings keep their places and the third child brings the count to three.
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
Growth may reallocate a vector and invalidate old references to its elements. Ask for the new size after appending.