Start learning free

LESSON 229 OF 667 · SETS

Sets in C++

Lesson

TL ; DR:

An unordered_set holds values without repeats. Inserting a value that is already in it changes nothing.


unordered_set<string> pets = {"cat", "dog", "cat"};   // cat goes in once

pets.insert("fish");                         // a new value

pets.insert("dog");                          // already in it, no change

cout << pets.size() << endl;                 // 3

cout << pets.count("dog") << endl;           // 1, so dog is in it


Full lesson:

A vector keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Inserting a value that is already in it changes nothing.

  • unordered_set<string> s; makes an empty set of strings.
  • s.insert(x) puts x in the set s.
  • s.count(x) is 1 when x is in the set, and 0 when it isn't.
  • s.size() gives how many values the set holds.
  • unordered_set<string> s(v.begin(), v.end()); builds a set from the vector v. Its repeats go in once.

Checking s.count(x) is fast, even for a big set. In a vector, you'd look at the values one by one.

C++17 sets have no contains. It only came in C++20. Test s.count(x) > 0 instead.

An unordered_set has no order and no indexes. s[0] doesn't compile.


Your task

The camp's sign-up vector, names, has some names twice. Build an unordered_set named kids from it.

Then Zoe signs up, and Ava signs up again. Insert both names into kids.

Last, if "Leo" is in kids, print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check