-
Notifications
You must be signed in to change notification settings - Fork 0
STL Map Set
Folder: 05-stl-map-set
The same roster problem from the previous lab, solved with associative containers. rosterMap.cpp keys a std::map by a custom Student type so each student maps to a list of course names. rosterSet.cpp puts students in a std::set to track who is enrolled. A third file, set.cpp, is a short demo of set and multiset behavior. The lesson is that an ordered associative container needs a way to compare keys, and a single operator< on the key type is enough.
Both roster programs define a Student holding a first and last name. The key line is the friend operator<, which orders by first name and then last name. Because std::map and std::set are ordered, they call that operator to place and find elements, so no separate comparator object is needed.
In rosterMap.cpp the container is map<Student, list<string>>. Reading a course file does roster[student].push_back(courseName), which inserts the student on first sight and appends the course. Dropouts are read into a vector and removed with map::erase. Printing walks the map in sorted order for free.
In rosterSet.cpp the container is set<Student>. Each course file inserts students, duplicates collapse automatically because a set holds one of each key, and dropouts are erased. The set version answers a simpler question (who is enrolled) and shows that the same comparator drives both containers.
set.cpp contrasts set and multiset: it inserts random characters into each, shows that the multiset keeps duplicates, then erases and searches to show count, erase, and find.
classDiagram
class Student {
-string firstName_
-string lastName_
+print() string
+operator<(Student, Student) bool
+operator==(Student, Student) bool
}
class StudentMap["map<Student, list<string>>"] {
+operator[](Student) list&
+erase(Student) size_t
}
class StudentSet["set<Student>"] {
+insert(Student) void
+erase(Student) size_t
+find(Student) iterator
}
StudentMap ..> Student : orders keys with operator<
StudentSet ..> Student : orders elements with operator<
g++ -std=c++17 05-stl-map-set/rosterMap.cpp -o rosterMap
./rosterMap cs1.txt cs2.txt cs3.txt cs4.txt dropouts.txt
g++ -std=c++17 05-stl-map-set/rosterSet.cpp -o rosterSet
./rosterSet cs1.txt cs2.txt cs3.txt cs4.txt dropouts.txtset.cpp is an instructor demo. The two roster programs are my work; solving the same problem with both a map and a set side by side is what makes the container trade-off concrete.
Data structures & STL
Design patterns