The Wayback Machine - https://web.archive.org/web/20240711181648/https://www.geeksforgeeks.org/unordered_multimap-and-its-application/
Open In App

unordered_multimap and its application

Last Updated : 28 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Allows Duplicates: 
We have discussed unordered_map in our previous post, but there is a limitation, we can not store duplicates in unordered_map, that is if we have a key-value pair already in our unordered_multimap and another pair is inserted, then both will be there whereas in case of unordered_map the previous value corresponding to the key is updated by the new value that is only would be there. Even can exist in unordered_multimap twice.

Internal Representation: 
The internal implementation of unordered_multimap is the same as that of unordered_map but for duplicate keys, another count value is maintained with each key-value pair. As pairs are stored in the hash table, there is no particular order among them but pairs with the same keys come together in the data structure whereas pairs with the same values are not guaranteed to come together. 

Time Complexity: 
All operation on unordered_multimap takes a constant amount of time on average but time can go to linear in the worst case depending on internally used hash function but in long run unordered_multimap outperforms multimap (tree-based multimap). 

Functions: 
unordered_multimap supports many functions which are demonstrated in the below code : 

CPP




// C++ program to demonstrate various function of
// unordered_multimap
#include <bits/stdc++.h>
using namespace std;
 
// making typedef for short declaration
typedef unordered_multimap<string, int>::iterator unit;
 
// Utility function to print unordered_multimap
void printUmm(unordered_multimap<string, int> umm)
{
    // begin() returns iterator to first element of map
    unit it = umm.begin();
 
    for (; it != umm.end(); it++){
        cout << "<" << it->first << ", " << it->second
             << ">  ";
        cout << endl;
    }
}
 
// Driver code
int main()
{
    // empty initialization
    unordered_multimap<string, int> umm1;
 
    // Initialization by initializer list
    unordered_multimap<string, int> umm2(
        { { "apple", 1 },
          { "ball", 2 },
          { "apple", 10 },
          { "cat", 7 },
          { "dog", 9 },
          { "cat", 6 },
          { "apple", 1 } });
 
    // Initialization by assignment operation
    umm1 = umm2;
    printUmm(umm1);
 
    // empty returns true, if container is empty else it
    // returns false
    if (umm2.empty())
        cout << "unordered multimap 2 is empty\n";
    else
        cout << "unordered multimap 2 is not empty\n";
 
    // size returns total number of elements in container
    cout << "Size of unordered multimap 1 is "
         << umm1.size() << endl;
 
    string key = "apple";
 
    // find and return any pair, associated with key
    unit it = umm1.find(key);
    if (it != umm1.end()) {
        cout << "\nkey " << key << " is there in unordered "
             << " multimap 1\n";
        cout << "\none of the value associated with " << key
             << " is " << it->second << endl;
    }
    else
        cout << "\nkey " << key
             << " is not there in unordered"
             << " multimap 1\n";
 
    // count returns count of total number of pair
    // associated with key
    int cnt = umm1.count(key);
    cout << "\ntotal values associated with " << key
         << " are " << cnt << "\n\n";
 
    printUmm(umm2);
 
    // one insertion by making pair explicitly
    umm2.insert(make_pair("dog", 11));
 
    // insertion by initializer list
    umm2.insert({ { "alpha", 12 }, { "beta", 33 } });
    cout << "\nAfter insertion of <alpha, 12> and <beta, "
            "33>\n";
    printUmm(umm2);
 
    // erase deletes all pairs corresponding to key
    umm2.erase("apple");
    cout << "\nAfter deletion of apple\n";
    printUmm(umm2);
 
    // clear deletes all pairs from container
    umm1.clear();
    umm2.clear();
 
    if (umm2.empty())
        cout << "\nunordered multimap 2 is empty\n";
    else
        cout << "\nunordered multimap 2 is not empty\n";
}


Output

<dog, 9>  
<cat, 6>  
<cat, 7>  
<ball, 2>  
<apple, 1>  
<apple, 10>  
<apple, 1>  
unordered multimap 2 is not empty
Size of unordered multimap 1 is 7

key apple is there in unordered  multimap 1

one of the value associated with apple is 1

total values associated with apple are 3

<dog, 9>  
<cat, 6>  
<cat, 7>  
<ball, 2>  
<apple, 1>  
<apple, 10>  
<apple, 1>  

After insertion of <alpha, 12> and <beta, 33>
<alpha, 12>  
<dog, 11>  
<dog, 9>  
<beta, 33>  
<cat, 6>  
<cat, 7>  
<ball, 2>  
<apple, 1>  
<apple, 10>  
<apple, 1>  

After deletion of apple
<alpha, 12>  
<dog, 11>  
<dog, 9>  
<beta, 33>  
<cat, 6>  
<cat, 7>  
<ball, 2>  

unordered multimap 2 is empty

As we can see in the above code most of the operations work similar to unordered_map but some things to note are : 
We can use the initializer list for initializing and inserting many pairs at once. 
There is no [] operator for unordered_multimap because values corresponding to a key are not unique, there can be many values associated with a single key so [] operator can not be applied to them. 
Erase function deletes all instances of values associated with the supplied key. 
Find function returns an iterator to any instance of key-value pair among all pairs associated with that key. 

How to access/delete a specific value for a key? 
If we want to check whether a specific value is there or not, we need to loop over all pairs of key-value until we get our specific value, if we get our specific value in the unordered_multimap then use erase(position) method to delete that specific value from unordered_multimap. 

CPP




// C++ program to erase particular value.
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to print unordered_multimap
void printUmm(unordered_multimap<string, int>& umm)
{
 
    // Iterator pointing to first element of unordered_map
    auto it1 = umm.begin();
 
    for (; it1 != umm.end(); it1++) {
        cout << "<" << it1->first << ", " << it1->second
             << ">  ";
        cout << endl;
    }
}
 
int main()
{
 
    // Initialization by initializer list
    unordered_multimap<string, int> umm{
        { "apple", 1 }, { "ball", 2 }, { "apple", 10 },
        { "cat", 7 },   { "dog", 9 },  { "cat", 6 },
        { "apple", 1 }
    };
 
    // Iterator pointing to first element of unordered_map
    auto it = umm.begin();
 
    // Search for an element with value 1
    while (it != umm.end()) {
        if (it->second == 1)
            break;
        it++;
    }
 
    // Erase the element pointed by iterator it
    if (it != umm.end())
        umm.erase(it);
     
      cout << "After deletion of value 1 from umm" << endl;
    printUmm(umm);
 
    return 0;
}


Output

After deletion of value 1 from umm
<dog, 9>  
<cat, 6>  
<cat, 7>  
<ball, 2>  
<apple, 10>  
<apple, 1>  

Methods of unordered_multimap: 

  • begin()– Returns an iterator pointing to the first element in the container or to the first element in one of its bucket.
  • end()– Returns an iterator pointing to the position after the last element in the container or to the position after the last element in one of its bucket.
  • count()– Returns the number of elements in the container whose key is equal to the key passed in the parameter.
  • cbegin()– Returns a constant iterator pointing to the first element in the container or to the first element in one of its bucket.
  • cend()– Returns a constant iterator pointing to the position after the last element in the container or to the position after the last element in one of its bucket.
  • clear() – Clears the contents of the unordered_multimap container.
  • size()– Returns the size of the unordered_multimap. It denotes the number of elements in that container.
  • swap()– Swaps the contents of two unordered_multimap containers. The sizes can differ of both the containers.
  • find()– Returns an iterator which points to one of the elements which have the key k.
  • bucket_size()– Returns the number of elements in the bucket n.
  • empty()– It returns true if the unordered_multimap container is empty. Otherwise, it returns false.
  • equal_range()– Returns the range in which all the element’s key is equal to a key.
  • operator=– Copy/Assign/Move elements from different container.
  • max_size()– Returns the maximum number of elements that the unordered_multimap container can hold.
  • load_factor()– Returns the current load factor in the unordered_multimap container.
  • key_eq()– Returns a boolean value according to the comparison.
  • emplace()– Inserts a new {key, element} in the unordered_multimap container.
  • emplace_hint()– Inserts a new {key:element} in the unordered_multimap container.
  • bucket_count()– Returns the total number of buckets in the unordered_multimap container.
  • bucket()– Returns the bucket number in which a given key is.
  • max_load_factor()– Returns the maximum load factor of the unordered_multimap container.
  • rehash()– Sets the number of buckets in the container to N or more.
  • reserve()– Sets the number of buckets in the container (bucket_count) to the most appropriate number so that it contains at least n elements.
  • hash_function()– This hash function is a unary function that takes a single argument only and returns a unique value of type size_t based on it.
  • max_bucket_count()– Returns the maximum number of buckets that the unordered multimap container can have.

Recent articles on unordered_multimap



Similar Reads

unordered_multimap begin() and end() function in C++ STL
The unordered_multimap::begin() is a built-in function in C++ STL that returns an iterator pointing to the first element in the container or to the first element in one of its buckets. Syntax: unordered_multimap_name.begin(n) Parameters: The function accepts one parameter. If a parameter is passed, it returns an iterator pointing to the first eleme
5 min read
unordered_multimap key_eq() function in C++ STL
unordered_multimap::key_eq() is a built-in function in C++ STL which returns a boolean value according to the comparison. It depends on the key equivalence comparison predicate used by the unordered_multimap container. The key equivalence comparison is a predicate which takes two arguments and returns a boolean value indicating whether they are to
2 min read
unordered_multimap hash_function() in C++ STL
The unordered_multimap::hash_function() is a built-in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it. Syntax: unordered_multimap_name.hash_function() Parameter: The function does not accept any parameter. Retu
2 min read
unordered_multimap max_bucket_count() function in C++ STL
The unordered_multimap::max_bucket_count() is a built-in function in C++ STL which returns the maximum number of buckets that the unordered multimap container can have. This is the maximum it can have, it cannot exceed despite the collisions due to certain limitations on it. Syntax: unordered_multimap_name.max_bucket_count() Parameter: The function
2 min read
unordered_multimap find() function in C++ STL
The unordered_multimap::find() is a built-in function in C++ STL which returns an iterator which points to one of the elements which has the key k. If the container does not contain any element with key k, then it returns an iterator which points to the position which is past the last element in the container. Syntax: unordered_multimap_name.find(k
3 min read
unordered_multimap load_factor() function in C++ STL
The unordered_multimap::load_factor() is a built-in function in C++ STL which returns returns the current load factor in the unordered_multimap container. The load factor is the ratio between the number of elements in the container (its size) and the number of buckets (bucket_count): load_factor = size / bucket_count The load factor influences the
3 min read
unordered_multimap equal_range() function in C++ STL
unordered_multimap::equal_range() is a built-in function in C++ STL which returns the range in which all the element's key is equal to a key. It returns a pair of iterators where the first is an iterator pointing to the lower bound of the range and second is an iterator pointing to the upper bound of the range. If there is no element equal to a giv
3 min read
unordered_multimap empty() function in C++ STL
The unordered_multimap::empty() is a built-in function in C++ STL which returns a boolean value. It returns true if the unordered_multimap container is empty. Otherwise, it returns false. Syntax: unordered_multimap_name.empty() Parameters: The function does not accept any parameter. Return Value: It returns a boolean value which denotes whether a u
2 min read
unordered_multimap emplace_hint() function in C++ STL
The unordered_multimap::emplace_hint() is a built-in function in C++ STL which inserts a new {key:element} in the unordered_multimap container. It starts searching from the position provided in the parameter for the insertion point of the element. The position only acts as a hint, it does not decide the position at which the insertion is to be done
2 min read
unordered_multimap emplace() function in C++ STL
The unordered_multimap::emplace() is a built-in function in C++ STL which inserts a new {key, element} in the unordered_multimap container. The insertion is done automatically at the position according to the container's criterion. It increases the size of the container by one. Syntax: unordered_multimap_name.emplace(key, element) Parameters: The f
2 min read
three90RightbarBannerImg