我有 2 个元素(目前)映射:
#define IDI_OBJECT_5001 5001
#define IDI_OBJECT_5002 5002
/.../
ResourcesMap[IDI_OBJECT_5001] = "path_to_png_file1";
ResourcesMap[IDI_OBJECT_5002] = "path_to_png_file2";
我正在尝试实现搜索此 map 的方法。我正在传递字符串参数(文件路径)和方法返回 int( map 的键值)
int ResFiles::findResForBrew(string filePath)
{
string value = filePath;
int key = -1;
for (it = ResourcesMap.begin(); it != ResourcesMap.end(); ++it)
{
if (/*checking if it->second == value */)
{
key = it->first;
break;
}
}
return key;
}
类 ResFiles { 民众: 资源文件(); ~ResFiles();
map <int, string> ResourcesMap;
map <int, string>::const_iterator it;
void filenamesForBrew();
int findResForBrew(string filePath);
private:
};
我如何检查 it->second-> == 值,然后返回那个键? 我将不胜感激。提前致谢。
最佳答案
这是一个基本的实现
template <typename K, typename V>
K keyFor(std::map<K, V> const& map, V const& target)
{
for (typename std::map<K, V>::const_iterator it=map.begin(); it!=map.end(); ++it)
if (it->second == target)
return it->first;
return K(); // or throw?
}
或者,在 C++11 支持下:
for (auto& pair : map)
if (pair.second == target)
return pair.first;
关于c++ - 按值搜索 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13582629/