c++ - 按值搜索 map

标签 c++ map

我有 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/

相关文章:

c++ - C++11 中递归元函数的延迟返回类型解析

带有 Map 和 For 的 Scala 迭代器

java - JPA - @OneToMany 作为 map

c++ - Qt:在新行上分离输入和显示

时间:2019-03-08 标签:c++wcfclientduplex

c++ - 为什么我的列表在上次函数调用后发生了变化?

c++ - 如何获得一个 friend 类的模板函数而不会出现错误

STL - STL map::find 函数在没有相等运算符的情况下如何工作?

database - 在 gps 跟踪中将地址保存到数据库

ios5 - MKPointAnnotation : title always visible. 可能吗?