c++ - 在 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())
解决方案
这个错误可能有点神秘。让我们把它翻译成人类可读的东西。
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)
。
推荐阅读
- python - 如何摆脱 MonthEnds 类型
- openmdao - 将 pyOptSparseDriver 与 OpenMDAO 和 WISDEM 一起使用
- javascript - Javascript setInterval 未按预期工作
- javascript - 在 JavaScript 中使用点表示法时调用(访问)(通过)(遍历)的每个元素的返回值
- java - 保存图片不压缩
- arrays - React/NextJS:如何映射键更改的对象数组?
- wordpress - Gatsbyjs + Wordpress GraphQL 错误`无法查询字段`
- html - 在 React 中,是否可以在上下文中存储 ref?
- c# - 例外:关联失败。未知位置异常:处理远程登录时遇到错误
- web-scraping - 如何抓取受 ColdFusion 保护的网站?