Learn C++ · lesson 31 of 61 · about 7 minutes
std::set
Explore the castle: keep the rooms visited in a std::set, so each one is on the map once and in sorted order.
What you'll learn
- Insert into a set
- Know duplicates are ignored
- Check membership and loop in order
Marking the map
The hero walks through the castle room by room, typing each room's name until done. Some rooms come up more than once, like the hall. A std::set<std::string> keeps each room once: when the hero walks back into a room it already holds, the adventure says so instead of adding it again. At the end, the set is the map of the castle, already in alphabetical order.
No duplicates, always sorted
std::set<int> s; (#include <set>) stores each value at most once, in sorted order.
s.insert(x)adds x (nothing happens if it's already there)s.contains(x)checks memberships.erase(x)removes it- Looping visits values from smallest to largest
Unique visitors
#include <iostream>
#include <set>
#include <string>
int main() {
std::set<std::string> visitors;
for (std::string name : {"Bo", "Ada", "Bo", "Cy", "Ada"}) visitors.insert(name);
std::cout << visitors.size() << " unique: ";
for (const auto& v : visitors) std::cout << v << " ";
std::cout << "\n" << std::boolalpha << visitors.contains("Cy") << "\n";
}Output
3 unique: Ada Bo Cy
trueTip
Need the counts as well as the unique values? That's a std::map<std::string, int>, coming up next.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.