🎓 A1Learner
🔍
0 of 34 lessons completed

C++ Unordered Containers

Unordered containers are collections that store values for fast lookup by key, with no sorted order. This lesson reads values by key and checks membership, and it never shows an order.

Reading values by key

Three pairs go into an unordered_map. The program reads two values back by naming their keys, so the printed order is the order of the reads.

#include <iostream>
#include <string>
#include <unordered_map>

int main() {
  std::unordered_map<std::string, int> ages;
  ages["Hana"] = 31;
  ages["Ana"] = 25;
  ages["Bo"] = 28;
  std::cout << "Ana: " << ages.at("Ana") << "\n";
  std::cout << "Hana: " << ages.at("Hana") << "\n";
  return 0;
}

count answers by key

count gives 1 for a key the map holds. count gives 0 for a key the map does not hold.

#include <iostream>
#include <string>
#include <unordered_map>

int main() {
  std::unordered_map<std::string, int> ages;
  ages["Ana"] = 25;
  ages["Bo"] = 28;
  ages["Hana"] = 31;
  std::cout << "Ana: " << ages.count("Ana") << "\n";
  std::cout << "Zoe: " << ages.count("Zoe") << "\n";
  return 0;
}

Size after inserts and an erase

The size prints 3 after three inserts. One erase then drops the size to 2, and a value that remains still reads back by its key.

#include <iostream>
#include <string>
#include <unordered_map>

int main() {
  std::unordered_map<std::string, int> ages;
  ages["Ana"] = 25;
  ages["Bo"] = 28;
  ages["Hana"] = 31;
  std::cout << "Size: " << ages.size() << "\n";
  ages.erase("Ana");
  std::cout << "Size: " << ages.size() << "\n";
  std::cout << "Bo: " << ages.at("Bo") << "\n";
  return 0;
}

Example

#include <iostream>
#include <string>
#include <unordered_set>

int main() {
  std::unordered_set<std::string> words;
  words.insert("pen");
  words.insert("ruler");
  words.insert("pen");
  std::cout << "Size: " << words.size() << "\n";
  std::cout << "pen: " << words.count("pen") << "\n";
  std::cout << "ruler: " << words.count("ruler") << "\n";
  std::cout << "glue: " << words.count("glue") << "\n";
  return 0;
}

Key points

  • An unordered_map stores a value for each key.
  • An unordered_set stores unique values with no key beside them.
  • at reads the value stored for a key.
  • count gives 1 when a key is present and 0 when a key is absent.
  • erase removes the entry for a key, and size gives how many entries remain.
  • Lookups by key are the main use of these containers.

In this example, three inserts name the word pen twice, so the set holds two unique words. count answers 1 for each stored word. count answers 0 for glue, a word the set never stored.

Note

No order is promised for the entries, so a program reads them by key and never by position.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does count give for a key that an unordered_map does not hold?