通过在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;发布于 2021-02-24 18:10:07
你不能。该映射的工作方式是对键进行散列,然后使用该键查找存储在内存中的值。它不允许您使用该值来索引键。
您可以做的是,遍历映射以找到值并从中获取键。
int key = 0;
int value = 4;
for(auto entry : m)
{
if(entry.second == value)
{
key = entry.first;
break; // Exit from the loop.
}
}参考:cppreference
发布于 2021-02-24 18:19:02
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;
}程序输出为
1562 4或者,您应该使用非标准容器,该容器允许通过键和值快速访问容器的元素。
发布于 2021-02-24 18:25:56
你也可以这样做:
#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 1562https://stackoverflow.com/questions/66348609
复制相似问题