← C++ from Scratch Lesson 58 of 62 · 10 XP

set

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

std::set is a sorted set without repeats. Under the hood it's a balanced (red-black) tree, so inserting, removing and searching are O(log n).

#include <set>

std::set<int> s = {5, 1, 5, 3};   // {1, 3, 5} — the repeat is dropped, in ascending order
s.insert(4);
s.count(3);                       // 1 — it's there; 0 — it isn't  (C++20 has s.contains(3))
s.erase(1);
*s.begin();  *s.rbegin();         // the minimum and the maximum
s.lower_bound(4);                 // an iterator to the first item ≥ 4

std::unordered_set is the same without the order, but faster on average (a hash table).

Task. Read two lists of words: first n and n words, then m and m words. Print on three lines (the words in alphabetical order, separated by spaces): the common words, the words only from the first list, and all the distinct words of both lists.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.