-
Notifications
You must be signed in to change notification settings - Fork 0
STL Vector List Move
Folder: 04-stl-vector-list-move
This folder switches from hand-built containers to the STL ones, and it adds move semantics. Two roster programs merge several course files into one list of students, removing anyone on a dropout list. A third program, moveIntArray.cpp, shows what a move constructor and move assignment buy you when an object owns a heap buffer.
roster.cpp keeps each student as a std::list<std::string> where the first element is the name and the rest are course names. The roster is a std::vector of those lists. For each student it uses std::find against the dropout list and std::find_if with a lambda to locate an existing entry, then either appends a course or pushes a new entry. A final std::sort orders the vector by name.
rosterObject.cpp does the same job but with a real Student class held directly in the containers. Student defines operator== and operator< over first then last name. The interesting part is that readRoster builds each Student and then std::moves it into the list, and the merge step moves students that are not already present. The class provides both a defaulted copy constructor and a hand-written move constructor that transfers the name strings and the course vector.
moveIntArray.cpp is the teaching case. MovableInt owns an int* buffer. It carries a copy constructor that allocates and copies, a move constructor that steals the pointer and nulls the source, a copy assignment, and a move assignment. The main pushes the object into a vector both by copy and with std::move, then prints the source after each so the difference is visible: after a move, the moved-from object is empty.
flowchart LR
A["MovableInt with heap buffer"] -->|copy push_back| B["new buffer allocated, bytes copied"]
A -->|move push_back| C["pointer transferred, source left empty"]
B --> D["source still holds its data"]
C --> E["source now size 0, no copy made"]
g++ -std=c++17 04-stl-vector-list-move/rosterObject.cpp -o roster
./roster cs1.txt cs2.txt cs3.txt cs4.txt dropouts.txt
g++ -std=c++17 04-stl-vector-list-move/moveIntArray.cpp -o move
./moveThe roster programs take a list of course files followed by the dropout file as the last argument.
moveIntArray.cpp is an instructor demo kept for reference. The two roster programs are mine, built on the STL containers and algorithms the course introduced in this lab.
Data structures & STL
Design patterns