In C++, multimap can store multiple values for a single key, and the elements are stored in an order of lowest to highest key value. In this article, we will discuss how to search for an element in a multimap in reverse order in C++
Example
Input: multimapp={{ 1, "One" }, { 2, "Two" }, { 1, "Second One" }, { 3, "Three" }, { 2, "Second Two" }} ; keyToSearch=2 Output: Found:2-> Second Two
Searching Multimap in Reverse Order in C++
To search multimap in reverse order for an element associated with some key, we can use the std::multimap::equal_range() which will return the pair of iterators where one points to the first element with the given key and the other points to the last element with the given key.
C++ Program for Searching Multimap in Reverse Order
The below example demonstrates the searching of multimap in reverse order using reverse iterators.
// C++ program to search a multimap in reverse order using // reverse iterators. #include <iostream> #include <map> using namespace std;
int main()
{ multimap< int , int > mm;
// Insert elements into the multimap
mm.insert({ 1, 100 });
mm.insert({ 2, 200 });
mm.insert({ 1, 300 });
mm.insert({ 2, 400 });
mm.insert({ 1, 500 });
// Find all elements with key 1
auto range = mm.equal_range(1);
// Create reverse iterators from the normal iterators
multimap< int , int >::reverse_iterator rit1(range.second);
// Iterate over the range in reverse order
cout << "Key: " << rit1->first << endl;
cout << "Value: " << rit1->second << endl;
return 0;
} |
Key: 1 Value: 500
Time Complexity: O(logN)
Auxiliary Space: O(1)