'How to get the key of a map using the value in C++ STL
Get key by inputting the value of that key in C++ STL
map<int,int> m;
m[0]=8;
m[8]=7;
m[1562]=4;
m[100]=1;
auto i=m.find(1562);
cout<<endl<<i->first;
Solution 1:[1]
You cant. The map works by hashing the key and then using that to find the value stored in memory. It does not allow you to use the value to index the key.
What you can do is, iterate through the map to find the value and get the key from it.
int key = 0;
int value = 4;
for(auto entry : m)
{
if(entry.second == value)
{
key = entry.first;
break; // Exit from the loop.
}
}
Reference: cppreference
Solution 2:[2]
std::map
is an ordered by key container. So to find a key by value you need to use the sequential search. For example you can use the standard algorithm std::find_if
.
Here is a demonstrative program.
#include <iostream>
#include <map>
#include <iterator>
#include <algorithm>
int main()
{
std::map<int,int> m =
{
{ 0, 8 }, { 8, 7 }, { 1562, 4 }, { 100, 1 }
};
int value = 4;
auto it = std::find_if( std::begin( m ), std::end( m ),
[&value]( const auto &p )
{
return p.second == value;
} );
if ( it != std::end( m ) )
{
std::cout << it->first << ' ' << it->second << '\n';
}
return 0;
}
The program output is
1562 4
Or you should use a non-standard container that allows a quick access to elements of the container by key and by value.
Solution 3:[3]
You may do it like this as well:
#include<iostream>
#include <map>
int findByValue(std::map<int, int> mapOfElemen, int value)
{
std::map<int, int>::iterator it = mapOfElemen.begin();
// Iterate through the map
while(it != mapOfElemen.end())
{
// Check if value of this entry matches with given value
if(it->second == value)
{
return it->first;
}
// Go to next entry in map
it++;
}
//key for the value is not found hou probably need to change this depending on your key space
return -9999;
}
int main()
{
std::map<int,int> m;
m[0]=8;
m[8]=7;
m[1562]=4;
m[100]=1;
int value = 1562;
int result = findByValue( m, value);
std::cout << "key for "<< value << " is " << result << std::endl;
value = 8;
result = findByValue( m, value);
std::cout << "key for "<< value << " is " << result << std::endl;
value = 7;
result = findByValue( m, value);
std::cout << "key for "<< value << " is " << result << std::endl;
}
The result would give this:
key for 1562 is -9999
key for 8 is 0
key for 7 is 8
key for 4 is 1562
Solution 4:[4]
You can use an unordered map:
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int,int> m = {{0,8},{8,7},{1562,4},{100,1}};
cout<<m[1562];
return 0;
}
This will print the output as 4.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | D-RAJ |
Solution 2 | Vlad from Moscow |
Solution 3 | |
Solution 4 | rax |