C++ Unordered Map Methods

Some common methods of the std::unordered_map class in C++ are:

  • insert(): Adds a new key-value pair to the map.
  • erase(): Removes a key-value pair from the map.
  • find(): Searches for a key in the map and returns an iterator to the corresponding value if found, or myMap.end() if not found.
  • count(): Returns the number of elements with a given key in the map (either 0 or 1, since keys must be unique).
  • empty(): Returns true if the map is empty, false otherwise.
  • size(): Returns the number of key-value pairs in the map.

Here's an example that demonstrates some of these methods:

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

int main() {
    std::unordered_map<std::string, int> myMap = {
        {"apple", 5},
        {"banana", 2},
        {"orange", 3}
    };

    // Insert a new key-value pair
    myMap.insert({"pear", 4});

    // Remove a key-value pair
    myMap.erase("banana");

    // Search for a key
    auto it = myMap.find("apple");
    if (it != myMap.end()) {
        std::cout << "Found " << it->first << " with value " << it->second << std::endl;
    } else {
        std::cout << "Key not found" << std::endl;
    }

    // Count the number of elements with a given key
    int numApples = myMap.count("apple");
    std::cout << "Number of apples: " << numApples << std::endl;

    // Check if the map is empty
    if (myMap.empty()) {
        std::cout << "Map is empty" << std::endl;
    } else {
        std::cout << "Map is not empty" << std::endl;
    }

    // Get the size of the map
    std::cout << "Map size: " << myMap.size() << std::endl;

    return 0;
}
Source:ww‮ditfigi.w‬ea.com

This program creates an std::unordered_map called myMap with four key-value pairs, and then performs various operations on the map using its methods. The output of the program is:

Found apple with value 5
Number of apples: 1
Map is not empty
Map size: 3