Skip to content

unordered_map

Initialization

  • Empty Unordered Map:
std::unordered_map<int, std::string> myMap;  // Empty unordered_map
  • brace initialization:
std::unordered_map<int, std::string> myMap = {
    {1, "one"},
    {2, "two"},
    {3, "three"}
};

Insert Elements

  • Insert Single Element:
myMap[1] = "one";  // Insert key-value pair
// or
myMap.insert(std::make_pair(1, "one"));  // Insert key-value pair

Access Elements

  • Access Value by Key:
std::string value = myMap[1];  // Access value by key, returns std::string
  • Find Element:
auto it = myMap.find(1);
// Returns iterator to the element if key exists, otherwise returns myMap.end()
it->first  # key
it->second # value

Removing Elements

  • Remove Element by Key:
myMap.erase(1);  // Removes element with key 1, returns number of elements removed (size_t)

Query Attributes

  • Get Map Size:
size_t size = myMap.size();  // Returns the number of elements in the map (size_t)
  • Check if Map is Empty:
bool isEmpty = myMap.empty();  // Returns true if the map is empty, otherwise false (bool)

Iterating through Unordered Map

  • Using Iterator:
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
    // it->first: key
    // it->second: value
}
  • Using Range-based For Loop:
for (const auto& [key, value] : myMap) {
    // key: key
    // value: value
}

Other Common Operations

  • Clear Map:
myMap.clear();  // Removes all elements from the map