Skip to main content

Section 5.6 Unordered Sets

An unordered_set is an unordered collection of zero or more unique C++ data values of a particular type. To use unordered_sets, you import unordered_set from the Standard template library with #include <unorderd_set>.
Unordered_sets allow for fast retrieval of individual elements based on their value. In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely. Keys are immutable, therefore, the elements in an unordered_set cannot be modified once in the container - However, they can be inserted and removed.
Unordered sets do not allow duplicates and are initialized using comma-delimited values enclosed in curly braces. The collection can be assigned to a variable as shown below.
set<int> mySet = {3, 6, 4, 78, 10}
Unordered sets support a number of methods that should be familiar to those who have worked with sets in a mathematics setting. Table 5.6.1 provides a summary. Examples of their use follow.
Table 5.6.1.
Method Name Use Explanation
union set_union() Returns a new set with all elements from both sets
intersection set_intersection() Returns a new set with only those elements common to both sets
difference set_difference() Returns a new set with all items from first set not in second
insert aset.insert(item) Adds item to the set
erase aset.erase(item) Removes item from the set
clear aset.clear() Removes all elements from the set
find aset.find(item) Find item in the set
The code below is an example of a program that can detect if a specific char is in an unordered set.
the find method used for a conditional in Checker compares each item in the set with the given parameter until there is a match. the set.find(letter) == set.end() section means that if find cannot find the letter before reaching the end of the set, then letter is not contained in the set.

Reading Questions Reading Question

1.

You have attempted 1 of 3 activities on this page.