Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::unordered_multimap — multiple values for one key

std::unordered_multimap stores key–value pairs and permits multiple entries with equivalent keys. It provides hash-based lookup but does not keep keys sorted. Use equal_range to retrieve every matching entry.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <unordered_map>
std::unordered_multimap<Key, T> entries;

std::unordered_multimap<Key, T> from <unordered_map> stores multiple values associated with equivalent keys. Unlike std::unordered_map, it permits repeated keys and even identical pairs. Its element type is std::pair<const Key, T>: an iterator can modify the mapped value, but not the key.

emplace adds an entry, find locates one matching element, and equal_range(key) returns the range [first, last) of all matches. erase(key) removes all matches and returns their count; erase(it) removes only the specified element. There is no operator[] or at.

Iteration order is unspecified, although equivalent keys form adjacent groups. find has average O(1) and worst-case O(n) complexity. Reading k matches additionally requires O(k). Equivalent keys must have the same hash. Rehashing invalidates iterators, but not pointers or references to elements.

The example collects the scores for "Ada" and sorts a copy so that output does not depend on iteration order. This entry targets C++23; the supplied standard draft is a living document, not a frozen C++23 specification. The repository compiler flag does not attest support in the production runtime environment.

Examples

#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

int main() {
    std::unordered_multimap<std::string, int> scores;
    scores.emplace("Ada", 20);
    scores.emplace("Ben", 15);
    scores.emplace("Ada", 10);

    const auto [first, last] = scores.equal_range("Ada");
    std::vector<int> values;
    for (auto it = first; it != last; ++it) {
        values.push_back(it->second);
    }
    std::sort(values.begin(), values.end());

    std::cout << "Ada:";
    for (int value : values) {
        std::cout << ' ' << value;
    }
    std::cout << '\n';
    std::cout << "removed: " << scores.erase("Ada") << '\n';
    std::cout << "remaining: " << scores.size() << '\n';
}

Result

Ada: 10 20
removed: 2
remaining: 1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources