Open In App

Search a Multimap in Reverse Order in C++

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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;
}


Output

Key: 1
Value: 500

Time Complexity: O(logN) 
Auxiliary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads