Search a Multimap in Reverse Order in C++
Last Updated :
08 Feb, 2024
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
multimap< int , int > mm;
mm.insert({ 1, 100 });
mm.insert({ 2, 200 });
mm.insert({ 1, 300 });
mm.insert({ 2, 400 });
mm.insert({ 1, 500 });
auto range = mm.equal_range(1);
multimap< int , int >::reverse_iterator rit1(range.second);
cout << "Key: " << rit1->first << endl;
cout << "Value: " << rit1->second << endl;
return 0;
}
|
Time Complexity: O(logN)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...