Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The C++ STL (Standard Template Library) supports several Data Structure that play a crucial role in solving any problem. One such data container is the "Multimap in C++". A multimap in C++ is an associative container that stores elements in a mapped fashion. Every element has one key value and one mapped value. Multiple elements can have the same key in a multimap.
This article will help you understand the multimap in c++ and the essential functions associated with it.
What is C++ Multimap?
A Multimap in c++ is very similar to a map with an addition that multiple items can have the same key value. Also, the key-value pair needs not be unique.
Internally, the elements of a multimap are always sorted by their key values following a specific ordering criterion indicated by its internal comparison object (of type Compare). Keys are always sorted in ascending order.
Multiple Keys: Allows storing multiple pairs with the same key.
Sorted Order: Automatically sorts elements by key in ascending order.
Key-Value Pairs: Stores elements as key-value pairs, similar to a regular map.
Duplicate Keys: Supports duplicate keys, unlike the std::map which requires unique keys.
Balanced Tree: Typically implemented as a balanced tree (e.g., red-black tree) for efficient insertion, deletion, and search operations.
Iterator Validity: Provides bidirectional iterators for traversing elements in sorted order.
How to Create a Multimap in C++?
We can easily create a multimap with the following syntax:
multimap<key_type , value_type> map_name;
The above code will create a multimap with a key of the "Key_type" data type and the "value_type" datatype value. Remember that the key of a multimap and corresponding values are always inserted as a pair. We cannot insert only a key or value in the map.
Now, let’s see an example of creating and initializing multimaps:
#include <bits/stdc++.h>
using namespace std;
int main ()
{
// Creates a multimap m with keys 3 having two different value
multimap<int,int> map_multi{ {1,4} , {2,5} , {3,6}, {3, 7} };
// Creates a multimap with keys of character type and values of integer type
multimap<string,int> map1;
map1["abc"]=101; // inserts key = "abc" with value = 101
map1["b"]=201; // inserts key = "b" with value = 201
map1["c"]=301; // inserts key = "c" with value = 301
map1["abc"]=401; // inserts key = "abc" with value = 401
// Create map map3 which is a copy of map m
multimap<char,int> map3 (map_multi.begin(), map_multi.end());
}
In the above example, we have created and initialized different multimaps with different methods.
Member Functions in C++ Multimap
For a multimap, many functions or methods are defined, among which the most used ones are the begin, end, empty and size for capacity, find for searching a key, erase and insert for modification.
Now let's learn about them in brief with the below table:
Function
Description
multimap::operator=
Assigns new contents to the multimap by replacing the existing ones.
multimap::crbegin() / crend()
Returns constant reverse iterators for iterating in reverse order.
multimap::emplace_hint()
Inserts the key-value pair with a hint about the position for insertion.
multimap::clear()
Removes all elements from the multimap.
multimap::empty()
Checks if the multimap is empty.
multimap::maxsize()
Returns the maximum number of elements the multimap can hold.
multimap::value_comp()
Returns the object that determines how elements are ordered (default: <).
multimap::rend()
Returns a reverse iterator pointing to the element before the first element.
multimap::cbegin() / cend()
Constant iterators to the first and the element after the last.
multimap::swap()
Swaps the contents of the current multimap with another of the same type.
multimap::rbegin()
Returns a reverse iterator pointing to the last element.
multimap::size()
Returns the number of elements in the multimap.
multimap::emplace()
Inserts a new key-value pair into the multimap.
multimap::begin() / end()
Iterators to the first element and the element after the last.
multimap::upper_bound()
Returns an iterator to the first element with a key greater than or equal to the given one.
multimap::count()
Returns the number of elements with a specific key.
multimap::erase()
Removes elements by key or iterator.
multimap::find()
Finds an element by key and returns an iterator to it.
multimap::equal_range()
Returns a pair of iterators indicating the range of elements with a given key.
multimap::insert()
Inserts a key-value pair into the multimap.
multimap::lower_bound()
Returns an iterator to the first element with a key not less than the given one.
multimap::key_comp()
Returns the object that defines how keys are compared.
Example of Multimap in C++
Let's consider an example of declaration, insert, find and iteration in a multimap.
C++
C++
#include <bits/stdc++.h> using namespace std;
int main () { // Creates a multimap m with keys 3 having two different value multimap<int,int> m{ {1,4} , {2,5} , {3,6}, {3, 7} };
// Using insert() method m.insert(pair<int,int> (4,7)); // Inserts new entry of key = 4 and value = 7 m.insert(make_pair(4, 8)); // Inserts new entry of key = 5 and value = 8
// Iterating over the multimap multimap<int, int>::iterator i; for(i = m.begin(); i != m.end(); i++){ cout << i->first << '\t' << i->second<< '\n'; } }
You can also try this code with Online C++ Compiler
An iterator to a multimap is an object (like a pointer) pointing to an element inside the multimap container. We can use these iterators to move through the elements of the container.
Syntax:
// Initializing an iterator
multimap<key_type , value_type>::iterator itr;
Example:
Let’s consider an example for iterating over the complete map in C++.
C++
C++
#include <bits/stdc++.h> using namespace std;
int main() { // Creates a map m with keys 1,2,3 and corresponding values 4,5,6 multimap<int,int> m{ {1,4} , {2,5} , {3,6} , {3, 7}};
// Iterating over the map multimap<int, int>::iterator i; for(i = m.begin(); i != m.end(); i++){ cout << i->first << '\t' << i->second<< '\n'; } }
You can also try this code with Online C++ Compiler
The output of the above code after iterating through the whole set is displayed below:
Output
Frequently Asked Questions
Why is multimap used?
Multimap in C++ is used when multiple values need to be associated with the same key, allowing storage and retrieval of duplicate keys in a sorted order efficiently.
Does multimap sort in C++?
Yes, std::multimap automatically sorts its elements by key in ascending order. It uses a red-black tree internally to maintain this sorted order.
What is the difference between multimap and map of sets in C++?
A std::multimap allows multiple elements with the same key and sorts elements by key. In contrast, a map of sets (std::map<Key, std::set<Value>>) stores unique keys and allows multiple values per key without sorting by value automatically.
How to reverse a multimap in C++?
You cannot directly reverse a std::multimap because it maintains elements in sorted order by key. To reverse the order of elements, you would typically need to copy the elements to another container and then reverse that container.
What is the difference between map and multimap in C++?
In C++, a map stores unique keys, while a multimap allows multiple elements with the same key. Both are associative containers, but a map ensures no duplicates, whereas a multimap can store several pairs with identical keys.
Conclusion
In this article, we have extensively discussed the multimap in C++. Understanding std::multimap in C++ provides developers with powerful capabilities for managing collections of key-value pairs where keys can have multiple associated values. With its automatic sorting by key and support for duplicate keys, std::multimap proves invaluable in scenarios requiring efficient storage and retrieval of structured data.