[英]How to get the key of a map using the value in C++ STL
通过在 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;
你不能。 map 通过对密钥进行哈希处理,然后使用它来查找存储在 memory 中的值。 它不允许您使用值来索引键。
您可以做的是,遍历 map 以查找值并从中获取密钥。
int key = 0;
int value = 4;
for(auto entry : m)
{
if(entry.second == value)
{
key = entry.first;
break; // Exit from the loop.
}
}
参考: cppreference
std::map
是按密钥排序的容器。 因此,要按值查找键,您需要使用顺序搜索。 例如,您可以使用标准算法std::find_if
。
这是一个演示程序。
#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;
}
程序 output 是
1562 4
或者您应该使用允许通过键和值快速访问容器元素的非标准容器。
你也可以这样做:
#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;
}
结果将给出:
key for 1562 is -9999
key for 8 is 0
key for 7 is 8
key for 4 is 1562
您可以使用无序的 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;
}
这会将 output 打印为 4。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.