【问题标题】:C++ unordered_map no matching member function for call to 'find' [duplicate]C ++ unordered_map没有匹配的成员函数来调用'find' [重复]
【发布时间】:2021-03-08 06:07:21
【问题描述】:

我正在尝试在 C++ 中初始化一个 unordered_map,然后运行 ​​find 命令,它一直失败并出现此错误,我不确定下一步该做什么。如果有帮助,这在 leetcode 中。

string num = "10003";
unordered_map<string,string> mymap = {
            {"0","0"},
            {"1","1"},
            {"6","9"},
            {"8","8"},
            {"9","6"},
        };
        unordered_map<string,string>::const_iterator got;
        for (auto s: num){
            mymap.find(s);
        }
Line 15: Char 19: error: no matching member function for call to 'find'
            mymap.find(s);
            ~~~~~~^~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unordered_map.h:920:7: note: candidate function not viable: no known conversion from 'char' to 'const std::unordered_map<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>, std::hash<std::string>, std::equal_to<std::__cxx11::basic_string<char>>, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>>>::key_type' (aka 'const std::__cxx11::basic_string<char>') for 1st argument
      find(const key_type& __x)
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unordered_map.h:924:7: note: candidate function not viable: no known conversion from 'char' to 'const std::unordered_map<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>, std::hash<std::string>, std::equal_to<std::__cxx11::basic_string<char>>, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>>>>::key_type' (aka 'const std::__cxx11::basic_string<char>') for 1st argument
      find(const key_type& __x) const
      ^
1 error generated.

【问题讨论】:

  • 轻松修复:mymap.find(std::string() + s));
  • @selbie 更简单:mymap.find(std::string{s}); 或只是 mymap.find({s});

标签: c++ c++11


【解决方案1】:

问题是您的密钥类型是std::string,但您将单个char 传递给find()std::string 没有constructor,它只接受一个char,因此出现错误。

还有其他方法可以从char 构造std::string,例如:

mymap.find(std::string(1,s));
mymap.find(std::string(&s,1));
mymap.find(std::string() + s);
using std::literals;
mymap.find(""s + s);
mymap.find({s});

【讨论】:

    【解决方案2】:

    s 是 char 类型,而您的地图具有 string 类型的键。改变一个或另一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多