首页 > 解决方案 > 在 C++ STL 的映射中搜索键时,出现以下错误

问题描述

我创建了一个 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;
      }
}

错误:

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())

标签: c++stlmaps

解决方案


这个错误可能有点神秘。让我们把它翻译成人类可读的东西。

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())

首先std::__cxx11::basic_string<char>是表示 a 的复杂方法std::string。然后__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&是一种更复杂的方式来表示它的返回类型s[i]实际上是 just char&。把它放在一起,我们得到

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())

我希望现在您可以看到该错误抱怨没有find将采用char&as 参数的重载。

相反,您应该传递一个std::string,例如 via s.substr(i,1)


推荐阅读