Sets
Sometimes you only care which values you have, not how many times each one appears. Which cities did your customers come from? Which tags are on a post? For this, C++ has the set.
A set is a collection where each value appears only once. If you add a value that is already there, nothing happens. To use sets, add #include <set> at the top.
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
set<string> cities;
cities.insert("Paris");
cities.insert("Delhi");
cities.insert("Paris");
cities.insert("Cairo");
cout << cities.size() << "\n";
for (string city : cities) {
cout << city << "\n";
}
return 0;
}
Output:
3
Cairo
Delhi
Paris
set<string> is a set of strings. insert adds a value. We inserted four values, but Paris was added twice, so the set keeps only one copy and its size is 3.
The loop printed the cities in alphabetical order, not in the order we added them. Like a map, a set always keeps its values sorted. With numbers, that means smallest first.
Checking and removing values
To check whether a value is in a set, use count. It returns 1 if the value is there and 0 if it is not. To remove a value, use erase.
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> seats = {12, 4, 9};
cout << seats.count(9) << "\n";
cout << seats.count(5) << "\n";
seats.erase(9);
cout << seats.count(9) << "\n";
cout << seats.size() << "\n";
return 0;
}
Output:
1
0
0
2
You can fill a set with values in curly braces, like a vector. Seat 9 was in the set, so count(9) gave 1. After erase(9), it gave 0, and the size went down to 2.
You may see seats.contains(9) in other C++ code. That function was added in C++20, and the compiler here uses C++17, so it is not available. Use count.
When to use a set
Use a set when duplicates should not count, or when you need the values in sorted order. A vector keeps every value you add, in the order you added it. A set throws away repeats and sorts what is left, with no extra code from you. If you do not need the sorted order, the next lesson shows a faster choice.
In the exercise, read a list of words into a set, then print how many different words there are and the words in sorted order.