Unordered multimap is an associative container. Same as unordered map it stores key and value pair. But unordered map doesn’t allow duplicate keys. Here duplicate keys are allowed. Since these are unordered containers, there is no order in the way of storing elements. But this allows duplicates so the elements which have same key are grouped together in the same bucket. For duplicate keys another count value is maintained with each key – value pair.
Since unordered multimap uses hash table to store key – value pairs, time complexity based on internal hash function used. It performs constant time in average case and in worst case it will take linear time for any operation.
Important methods of Unordered Multimap
- iterator begin() noexcept;
const_iterator begin() const noexcept;
Returns an iterator pointing to the first element in the unordered_multimap container (1). - void clear() noexcept;
All the elements in the unordered_multimap container are dropped: their destructors are called, and they are removed from the container, leaving it with a size of 0. - iterator end() noexcept;
const_iterator end() const noexcept;
Returns an iterator pointing to the past-the-end element in the unordered_multimap container. - iterator find ( const key_type& k );
const_iterator find ( const key_type& k ) const;
Searches the container for an element with k as key and returns an iterator to it if found, otherwise it returns an iterator to unordered_multimap::end (the element past the end of the container). - size_type size() const noexcept;
Returns the number of elements in the unordered_multimap container.
Example
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main () { unordered_multimap <string, int> unmmp1; unordered_multimap <string, int> :: iterator it; // Direct assigning key - value pairs unmmp1 = { {"H", 264} , {"I" , 237}}; // inserting using "initializor list" function unmmp1.insert ( {{"S" , 219} , {"M" , 215}} ); // making pair and inserting pair <string, int> hit2 ("H" , 209); unmmp1.insert (hit2); // moving pair unmmp1.insert (make_pair <string, int> ("H" , 208)); // Print unordered multimap for (it= unmmp1.begin(); it!= unmmp1.end(); ++it) { cout << it->first << it->second << endl; } // Erasing first pair unmmp1.erase (unmmp1.begin()); // Erasing record contains key I unmmp1.erase ("I"); // Checking unordered multi map empty or not bool chk= unmmp1.empty(); // Find value of key cout << unmmp1.find("H")->second; // Size of map cout << unmmp1.size(); // Clearing the map unmmp1.clear(); return 0; }