Start learning free

LESSON 233 OF 667 · SETS

Removing from a Set and Looping Over It in C++

Lesson

TL ; DR:

erase(x) takes x out of a set. A range-based for loop visits every value once, in no fixed order.


unordered_set<string> colors = {"red", "blue", "green"};

colors.erase("blue");

colors.erase("pink");           // not in it, nothing happens

for (string color : colors) {
    cout << color << endl;      // red and green, in any order
}


Full lesson:

s.erase(x) removes x from the set s. It returns how many values it removed. That is 1 if x was there, and 0 if it wasn't.

for (string x : s) visits each value of the set once. The order isn't fixed. That's what the "unordered" in unordered_set means.

So loop over a set when the order doesn't matter. A total, a count and a check are fine.

Don't erase values from a set while you loop over it. The loop loses its place, and the program may crash. Erase first, then loop.


Your task

In a word game, the set found holds the words a player found. The words "qqq" and "zzz" aren't allowed. Remove both from found.

The player never found "zzz", so removing it changes nothing.

Then add up the points. A word scores one point per letter. Loop over found and add each word's length to score.

The code already prints how many words are left, and the points.

Expected output:

4 words
14 points
STEP 1 OF 3
    Ctrl + Enter to check