简体   繁体   English

在C ++ STL中搜索映射中的键时,出现以下错误

[英]While Searching for a key in a map in C++ STL, gives the following error

I have a created a Map with key as string type and the associated value stored in vector. 我创建了一个Map,键为字符串类型,关联值存储在vector中。 Now I have a string and need to check if the each of the character in the string is present as a key in the map. 现在,我有一个字符串,需要检查字符串中的每个字符是否在映射中作为键出现。

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <map>
#include <string>
using namespace std;

int main() {
   map<string, vector<string>> umap;
   umap["1"] = {"a","b","c"};
   umap["2"] = {"d","e","f"};
   string s = "23";
   for(int i=0; i<s.length(); i++) {
      if(umap.find(s[i]) != umap.end()) 
          cout<<"Present"<<endl;
      else
          cout<<"Not Present"<<endl;
      }
}

Error: 错误:

main.cpp: In function ‘int main()’:
main.cpp:15:26: error: no matching function for call to ‘std::map<std::__cxx11::basic_string<char>, std::vector<std::__cxx11::basic_string<char> > >::find(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)’
         if(umap.find(s[i]) != umap.end())

The error is maybe a bit cryptic. 该错误可能有点神秘。 Lets translate it into something human readable. 让我们将其转换为人类可读的内容。

main.cpp: In function ‘int main()’:
main.cpp:15:26: error: no matching function for call to ‘std::map<std::__cxx11::basic_string<char>, std::vector<std::__cxx11::basic_string<char> > >::find(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)’
         if(umap.find(s[i]) != umap.end())

First std::__cxx11::basic_string<char> is a complicated way to denote a std::string . 第一个std::__cxx11::basic_string<char>是表示std::string一种复杂方法。 Then __gnu_cxx::__alloc_traits<std::allocator<char> >::value_type& is an even more complicated way to denote the return type of s[i] which is actually just char& . 然后__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&是表示s[i]的返回类型(实际上只是char&更为复杂的方法。 Putting this together we get 放在一起我们得到

main.cpp: In function ‘int main()’:
main.cpp:15:26: error: no matching function for call to ‘std::map<std::string, std::vector<std::string> >::find(char&)’
         if(umap.find(s[i]) != umap.end())

I hope now you can see that the error complains that there is no overload of find that would take a char& as parameter. 我希望现在您可以看到该错误抱怨没有将char&作为参数的find重载。

Instead you should pass a std::string , eg via s.substr(i,1) . 相反,您应该通过s.substr(i,1)传递std::string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM