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 6 provides a summary. Examples of their use follow.

Table 6: Methods Provided by Sets in C++
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
add aset.insert(item) Adds item to the set
remove aset.erase(item) Removes item from the set
clear aset.clear() Removes all elements from the set

5.7. Summary

  1. A statically allocated C++ array is an ordered collection of one or more C++ data values of identical type stored in contiguous memory.
  2. A vector is a dynamically allocated array with many useful methods. It is more similar to the Python list than the array.
  3. C++ strings are a sequential collection of zero or more characters. They are very similar to Python strings.
  4. A hash table is used to store keys-value pairs. It applies a related hash function to the key in order to compute the location of the associated value. Look-up is typically very fast.
  5. A set is an unordered collection of unique values.

5.8. Check Yourself

    Q-1: Which C++ structure is the best choice for a group of ordered data of a fixed length?
  • array
  • Correct!
  • hash table
  • No. hash tables are not ordered.
  • string
  • A string would only work for character data. Try again.
  • vector
  • There is a better choice given that the group is fixed length
  • more than one of the above
  • Only of the above is best.
    Q-2: Drag each data type to its' corresponding C++ initialization syntax. Feedback shows incorrect matches.
  • Array
  • {“What”, “am”, “I”, "am"}
  • Set
  • {“What”, “am”, “I”}
  • String
  • “What am I”
  • Hash Table
  • {{“What”, “am I”}}
Next Section - 5.9. Glossary