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.
#include <iostream> #include <map>
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:
myMultimap: This is the name you give your specific multimap variable.
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
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; }
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; }
Remove elements from the multimap using the erase function.
myMultimap.erase(1); // Removes all elements with key 1
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;
C++ Multimap Tutorial
STL Multimap in C++
Multimap Implementation Example
Sorted Associative Container C++
C++ Multimap Usage Guide
Multimap vs Map in C++
STL Containers in C++
C++ Multimap Insert and Erase Operations
C++ Multimap Iterator Functions
Best Practices for Using Multimap in C++
STL Multimap
Comprehensive Guide
C++ Multimap Tutorial