STL Multimap in C++

A multimap in C++ is a type of associative container provided by the Standard Template Library (STL). It is similar to a regular map, but it allows multiple elements with the same key. Each element in a multimap consists of a key-value pair, and you can have multiple key-value pairs with the same key.

Necessary Header

#include <iostream>
#include <map>

Declaration of Multimap

Declare a multimap with a specific key and value type.

std::multimap<int, std::string> myMultimap;

std::multimap: This indicates you're creating a multimap, a type of associative container in the C++ Standard Template Library (STL).
<int, std::string>: These are the template parameters specifying the data types within the multimap:

  • int: This is the data type for the keys. Your multimap will use integer keys to organize the data.
  • std::string: This is the data type for the values. Each key can be associated with multiple string values.

myMultimap: This is the name you give your specific multimap variable.

Inserting a element

Insert key-value pairs into the multimap using the insert function.

myMultimap.insert(std::make_pair(1, "Apple"));
myMultimap.insert(std::make_pair(2, "Banana"));
myMultimap.insert(std::make_pair(1, "Apricot"));  // Allows duplicates with the same key

Accessing Elements

You can access elements in the multimap using iterators.

// Print all elements in the multimap
for (auto it = myMultimap.begin(); it != myMultimap.end(); ++it) {
    std::cout << it->first << ": " << it->second << std::endl;
}

Finding Elements

Use the find function to search for elements with a specific key.

auto range = myMultimap.equal_range(1);
for (auto it = range.first; it != range.second; ++it) {
    std::cout << "Found element with key 1: " << it->second << std::endl;
}

Erasing Elements

Remove elements from the multimap using the erase function.

myMultimap.erase(1);  // Removes all elements with key 1

Size and Empty

You can check the size of the multimap using size() and whether it's empty using empty().

std::cout << "Size of multimap: " << myMultimap.size() << std::endl;
std::cout << "Is multimap empty? " << (myMultimap.empty() ? "Yes" : "No") << std::endl;