Given a multimap and a key of the multimap, our task is to simply display the (key – value) pairs of the given key. In multimap we can have multiple (key – value) pair for the same key. Suppose our multimap contains
key value 1 10 2 20 2 30 2 40 3 50 4 60 4 70 key : 2 key value 2 20 2 30 2 40
Like in unordered_map in C++ STL we cant fetch values like
int key = 2; multimap map; // insert values in map cout << "Key : " << key; cout << "Value : " <
Key : 2 Value : 20
Because the above method will only return the first occurrence of the key present, This method fails if there are multiple (key – value) pairs for the same key.
There are two ways by which we can achieve the expected results :
Method 1 (Simple Traversal) Traverse through whole map and whenever the key is equal to given key we display the key-value pair.
2 20 2 30 2 40
Method 2(Using Binary Search)Find the lower_bound and upper_bound for the given key and traverse between them.
lower_bound(key) : returns the iterator pointing to the first element which is greater than or
equal to key.
upper_bound(key) : returns the iterator pointing to the first element which is greater than key.
key value 1 10 2 20 <-- lower_bound(20) 2 30 2 40 3 50 <-- upper_bound(20) 4 60 4 70
2 20 2 30 2 40
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- multimap::cbegin() and multimap::cend() in C++ STL
- multimap::crbegin() and multimap::crend() in C++ STL
- multimap::begin() and multimap::end() in C++ STL
- How to traverse a C++ set in reverse direction
- How to traverse a STL map in reverse direction?
- multimap maxsize() in C++ STL
- multimap insert() in C++ STL
- multimap equal_range() in C++ STL
- multimap operator = in C++ STL
- multimap::count() in C++ STL
- multimap::erase() in C++ STL
- multimap find() in C++ STL
- multimap::emplace_hint() in C++ STL
- multimap key_comp in C++ STL
- multimap::operator= in C++ STL
- multimap::swap() in C++ STL
- multimap::emplace() in C++ STL
- multimap key_comp() in C++ STL
- multimap rend in C++ STL
- multimap rbegin in C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.