0

I'm trying to initialize an unordered_map in c++ and then run the find command, it keeps failing with this error and I'm not sure what to do next. This is in leetcode if that helps.

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.

2 Answers2

1

The problem is that your key type is std::string, but you are passing a single char to find(). std::string does not have a constructor that accepts only a single char, hence the error.

There are other ways to construct a std::string from a char, eg:

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});
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

s is of type char, while your map has key's of type string. Change one or the other.

acraig5075
  • 10,588
  • 3
  • 31
  • 50