【问题标题】:While Searching for a key in a map in C++ STL, gives the following error在 C++ STL 的映射中搜索键时,出现以下错误
【发布时间】:2019-07-02 08:50:47
【问题描述】:

我创建了一个 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())

【问题讨论】:

  • s[i] 不是std::string,而是char
  • 试试umap.find(s.substr(i, 1))...

标签: c++ stl maps


【解决方案1】:

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

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&lt;char&gt; 是表示std::string 的复杂方式。那么__gnu_cxx::__alloc_traits&lt;std::allocator&lt;char&gt; &gt;::value_type&amp; 是一种更复杂的方式来表示s[i] 的返回类型,它实际上只是char&amp;。把这些放在一起,我们得到

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&amp; 作为参数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-13
    • 2013-04-30
    • 2016-02-20
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2014-09-27
    • 2011-03-17
    相关资源
    最近更新 更多