Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::multimap — ordered pairs with duplicate keys

std::multimap from <map> stores key–value pairs in key order and allows multiple elements with equivalent keys. equal_range retrieves the entire matching group, while erase(key) removes every element in that group.

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

Syntax

#include <map>
std::multimap<Key, T> name;
std::multimap<Key, T, Compare> name;

std::multimap<Key, T> from <map> is an ordered associative container. Unlike std::map, it allows multiple elements with equivalent keys. Iteration follows Compare, which defaults to std::less<Key>. The comparator must define a strict weak ordering; equivalence means !comp(a, b) && !comp(b, a), not necessarily a == b.

An element has type std::pair<const Key, T>: an iterator lets you modify the mapped value, but not the key. Ordinary emplace appends an element to the group of equivalent keys. std::multimap provides neither operator[] nor at; it does not automatically choose one value for a key.

equal_range(key) returns two iterators delimiting the half-open range of all matches; no matches means an empty range. find(key) returns only one match or end(). erase(key) removes all matches and returns their count; erase(it) removes one selected element. For N elements, lookup and ordinary insertion take O(log N), and traversing K matches after equal_range takes O(log N + K) overall.

In the example, the two calls to emplace for key 2 preserve the order review, test; removing that group leaves one element. The example targets C++23. The supplied document is an evolving draft, not a frozen C++23 edition; newer declarations in the draft do not establish C++23 availability. A repository compiler flag does not attest the production runtime.

Examples

#include <iostream>
#include <map>
#include <string>

int main() {
    std::multimap<int, std::string> tasks;
    tasks.emplace(2, "review");
    tasks.emplace(1, "build");
    tasks.emplace(2, "test");

    const auto [first, last] = tasks.equal_range(2);
    for (auto it = first; it != last; ++it) {
        std::cout << it->first << ": " << it->second << '\n';
    }
    std::cout << "removed: " << tasks.erase(2) << '\n';
    std::cout << "remaining: " << tasks.size() << '\n';
}

Result

2: review
2: test
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