How to traverse through all values for a given key in multimap? Last Updated : 06 Apr, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report 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 value1 102 202 302 403 504 604 70key : 2key value2 202 302 40Like in unordered_map in C++ STL we cant fetch values like int key = 2;multimap map;// insert values in mapcout << "Key : " << key;cout << "Value : " < second;Output : Key : 2Value : 20Because 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. C++ // CPP program to find all values for a // given key. #include <bits/stdc++.h> using namespace std; int main() { multimap <int, int> map; // insert the values in multimap map.insert(make_pair(1, 10)); map.insert(make_pair(2, 20)); map.insert(make_pair(2, 30)); map.insert(make_pair(2, 40)); map.insert(make_pair(3, 50)); map.insert(make_pair(4, 60)); map.insert(make_pair(4, 70)); int key = 2; for (auto itr = map.begin(); itr != map.end(); itr++) if (itr -> first == key) cout << itr -> first << " " << itr -> second << endl; return 0; } Java // JAVA program to find all values for a // given key. import java.util.*; class GFG { static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } public static void main(String[] args) { HashSet <pair> map = new LinkedHashSet<>(); // add the values in multimap map.add(new pair(1, 10)); map.add(new pair(2, 20)); map.add(new pair(2, 30)); map.add(new pair(2, 40)); map.add(new pair(3, 50)); map.add(new pair(4, 60)); map.add(new pair(4, 70)); int key = 2; for (pair itr : map) if (itr.first == key) System.out.println(itr.first+ " " + itr.second); } } // This code is contributed by 29AjayKumar Python3 # Python program to find all values for a # given key. map = [] # insert the values in multimap map.append((1, 10)); map.append((2, 20)); map.append((2, 30)); map.append((2, 40)); map.append((3, 50)); map.append((4, 60)); map.append((4, 70)); key = 2; for i in map: if i[0] == key: print(i[0],i[1]) # This code is contributed by shubhamsingh10 C# // C# program to find all values for a // given key. using System; using System.Collections.Generic; class GFG { class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Driver code public static void Main(String[] args) { HashSet<pair> map = new HashSet<pair>(); //.Add the values in multimap map.Add(new pair(1, 10)); map.Add(new pair(2, 20)); map.Add(new pair(2, 30)); map.Add(new pair(2, 40)); map.Add(new pair(3, 50)); map.Add(new pair(4, 60)); map.Add(new pair(4, 70)); int key = 2; foreach (pair itr in map) if (itr.first == key) Console.WriteLine(itr.first+ " " + itr.second); } } // This code is contributed by Rajput-Ji JavaScript <script> class pair { constructor(first,second) { this.first=first; this.second=second; } } let map = new Set(); // add the values in multimap map.add(new pair(1, 10)); map.add(new pair(2, 20)); map.add(new pair(2, 30)); map.add(new pair(2, 40)); map.add(new pair(3, 50)); map.add(new pair(4, 60)); map.add(new pair(4, 70)); let key = 2; for (let itr of map.values()) if (itr.first == key) document.write(itr.first+ " " + itr.second+"<br>"); // This code is contributed by rag2127 </script> Output: 2 202 302 40Method 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 value1 102 20 <-- lower_bound(2)2 302 403 50 <-- upper_bound(2)4 604 70 CPP #include <bits/stdc++.h> using namespace std; int main() { multimap <int, int> map; // insert the values in multimap map.insert(make_pair(1, 10)); map.insert(make_pair(2, 20)); map.insert(make_pair(2, 30)); map.insert(make_pair(2, 40)); map.insert(make_pair(3, 50)); map.insert(make_pair(4, 60)); map.insert(make_pair(4, 70)); int key = 2; auto itr1 = map.lower_bound(key); auto itr2 = map.upper_bound(key); while (itr1 != itr2) { if (itr1 -> first == key) cout << itr1 -> first << " " << itr1 -> second << endl; itr1++; } return 0; } Java import java.util.*; public class Main { public static void main(String[] args) { Map<Integer, List<Integer>> map = new HashMap<>(); // Insert the values in the map map.put(1, Arrays.asList(10)); map.put(2, Arrays.asList(20, 30, 40)); map.put(3, Arrays.asList(50)); map.put(4, Arrays.asList(60, 70)); int key = 2; // Print the values for the specific key if (map.containsKey(key)) { for (int value : map.get(key)) { System.out.println(key + " " + value); } } } } Python3 from collections import defaultdict # Create a defaultdict with int as the default factory map = defaultdict(list) # insert the values in the multimap map[1].append(10) map[2].extend([20, 30, 40]) map[3].append(50) map[4].extend([60, 70]) key = 2 itr1 = map[key] for val in itr1: print(key, val) C# using System; using System.Collections.Generic; class MainClass { public static void Main (string[] args) { Dictionary<int, List<int>> map = new Dictionary<int, List<int>>(); // Insert the values in the map map.Add(1, new List<int> { 10 }); map.Add(2, new List<int> { 20, 30, 40 }); map.Add(3, new List<int> { 50 }); map.Add(4, new List<int> { 60, 70 }); int key = 2; // Print the values for the specific key if (map.ContainsKey(key)) { foreach (int value in map[key]) { Console.WriteLine(key + " " + value); } } } } JavaScript // Create a JavaScript object to store the values const map = { 1: [10], 2: [20, 30, 40], 3: [50], 4: [60, 70] }; const key = 2; // Check if the key exists in the map if (map.hasOwnProperty(key)) { // Print the values for the specific key map[key].forEach(value => { console.log(key + " " + value); }); } Output: 2 202 302 40Time complexity: O(logn) where n is size of given multimap Auxiliary Space: O(n) Comment More infoAdvertise with us F foreverrookie Follow Improve Article Tags : DSA STL cpp-multimap Practice Tags : STL Similar Reads Multimap in C++ STL In C++, multimap is an associative container similar to map, but it can have multiple elements with same keys. It stores all the elements in increasing order based on their keys by default but can be changed if required. It provides fast insertion, deletion and search on this sorted data.Example:CPP 8 min read Commonly Used Methodsmultimap::begin() and multimap::end() in C++ STLmultimap::begin() is a built-in function in C++ STL that returns an iterator referring to the first element in the multimap container. Since the multimap container contains the element in an ordered way, begin() will point to that element that will come first according to the container's sorting cri 3 min read multimap size() function in C++ STLThe multimap::size() is a built-in function in C++ STL which returns the number of elements in the multimap container. Syntax: multimap_name.size() Parameters: The function does not accept any parameter. Return Value: This function returns the number of elements a multimap container has. CPP // C++ 1 min read multimap empty() function in C++ STLThe multimap::empty() is a boolean type observer function in C++ STL which tells whether the container is empty or not. This function returns true when the multimap container is empty (i.e. the size of the container is 0). Being an observer function it does not modify the multimap in any way. Syntax 1 min read multimap insert() in C++ STLThe multimap::insert is a built-in function in C++ STL that is used to insert elements in the multimap container. Syntax: iterator multimap_name.insert({key, element}) Parameters: The function accepts a pair that consists of a key and element which is to be inserted into the multimap container. Retu 2 min read multimap::emplace() in C++ STLThe multimap::emplace() is a built-in function in C++ STL which inserts the key and its element in the multimap container. It effectively increases the container size by one as multimap is the container that stores multiple keys with same values. Syntax: multimap_name.emplace(key, element) Parameter 1 min read multimap find() in C++ STLmultimap::find() is a built-in function in C++ STL which returns an iterator or a constant iterator that refers to the position where the key is present in the multimap. In case of multiple same keys being present, the iterator that refers to one of the keys (typically the first one). In case we wis 2 min read multimap::count() in C++ STLThe multimap::count is a built-in function in C++ STL which returns the number of times a key is present in the multimap container. Syntax: multimap_name.count(key) Parameters: The function accepts one mandatory parameter key which specifies the key whose count in multimap container is to be returne 1 min read multimap::erase() in C++ STLmultimap::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range. Syntax for erasing a key: multimap_name.erase(key) Parameters: The function accepts one mandatory parameter key wh 4 min read multimap clear() function in C++ STLThe multimap clear() function is an inbuilt function in C++ STL which is used to remove all elements from the multimap container (which are destroyed), leaving the container with a size of 0. Syntax : mymultimap_name.clear() Parameters: This function does not take any arguments. Return Value: This f 2 min read multimap::swap() in C++ STLmultimap::swap() is used to swap the contents of one multimap with another multimap of same type and size. Syntax:- multimap1.swap(multimap2) Parameters : The name of the multimap with which the contents have to be swapped. Result : All the elements of the 2 multimap are swapped. Examples: Input: mu 2 min read Other Member Methodsmultimap maxsize() in C++ STLThe multimap::max_size() is a built-in function in C++ STL which returns the maximum number of elements a multimap container can hold. Syntax: multimap_name.max_size() Parameters: This function does not accept any parameters. Return Value: This function returns the maximum number of elements a list 1 min read multimap equal_range() in C++ STLThe multimap::equal_range() is a built-in function in C++ STL which returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both 2 min read multimap upper_bound() function in C++ STLThe multimap::upper_bound(k) is a built-in function in C++ STL which returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to key+1 and element=0. Syntax: 2 min read multimap lower_bound() function in C++ STLThe multimap::lower_bound(k) is a built-in function in C++ STL which returns an iterator pointing to the key in the container which is equivalent to k passed in the parameter. In case k is not present in the multimap container, the function returns an iterator pointing to the immediate next element 2 min read multimap rbegin in C++ STLmultimap::rbegin() is a built-in-function in C++ STL which returns an iterator pointing to the last element of the container. Syntax: multimap_name.rbegiin() Parameters: The function does not take any parameter. Return Value: The function returns a reverse iterator pointing to the last element of th 2 min read multimap::cbegin() and multimap::cend() in C++ STLmultimap::cbegin() is a built-in function in C++ STL which returns a constant iterator referring to the first element in the multimap container. Since multimap container contains the element in an ordered way, cbegin() will point to that element that will come first according to the container's sort 3 min read multimap rend in C++ STLmultimap::rend() is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element preceding to the first element of the multimap container. Syntax multimap_name.rend() Parameters: The function does not take any parameter. Return ValueThe function returns a rever 2 min read multimap value_comp() function in C++ STLThe multimap::value_comp() method returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second. Here the 1st object compares the object of type std::multimap::type. The arguments taken by this function object are of member type t 2 min read multimap::emplace_hint() in C++ STLThe multimap::emplace_hint() is a built-in function in C++ STL which inserts the key and its element in the multimap container with a given hint. It effectively increases the container size by one as multimap is the container that stores multiple keys with same values. The hint provided does not aff 2 min read multimap::crbegin() and multimap::crend() in C++ STLmultimap::crbegin() is a built-in function in C++ STL which returns a constant reverse iterator referring to the last element in the multimap container. Since multimap container contains the element in an ordered way, crbegin() will point to that element that will come last according to the containe 3 min read multimap::operator= in C++ STLmultimap::operator= is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new contents. Syntax:- multimap1 = (multimap2) Parameters : Another container of the same type. Result : Assign the contents of the container passed as p 2 min read multimap key_comp() in C++ STLThe std::multimap::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container.By default, this is a less object, which returns the same as operator â<'.It is a function pointer or a function object which takes two arguments of the same ty 2 min read Multimap of pairs in C++ with Examples What is a multimap? In C++, a multimap is an associative container that is used to store elements in a mapped fashion. Internally, a multimap is implemented as a red-black tree. Each element of a multimap is treated as a pair. The first value is referred to as key and the second value is referred to 5 min read Multimap of tuples in C++ with Examples What is a multimap? In C++, a multimap is an associative container that is used to store elements in a mapped fashion. Internally, a multimap is implemented as a red-black tree. Each element of a multimap is treated as a pair. The first value is referred to as key and the second value is referred to 6 min read Difference between pair in Multiset and Multimap in C++ STL Pairs in C++: The pair container is a simple container defined in <utility> header consisting of two data elements or objects. The first element is referenced as âfirstâ and the second element as âsecondâ and the order is fixed (first, second). Pair is used to combine together two values which 5 min read Multimap vs Map in C++ STL with Examples Map in C++ STL Map stores unique key-value pairs in a sorted manner. Each key is uniquely associated with a value that may or may not be unique. A key can be inserted or deleted from a map but cannot be modified. Values assigned to keys can be changed. It is a great way for quickly accessing value u 8 min read Common Multimap ProblemsDescending Order in Map and Multimap of C++ STLWe have discussed map in C++ STL and multimap in C++ STL. The default behavior of these data structures is to store elements in ascending order. How to store elements in reverse order or descending order when inserting in map and multimap? We can use the third parameter, that is std::greater along w 3 min read How to traverse through all values for a given key in multimap?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 value1 102 202 302 403 504 604 70key : 2key value2 202 302 40Like in unordered_m 5 min read Like