【问题标题】:C++ map no matching member function for call to 'find' when used for a string当用于字符串时,C++ 映射没有匹配的成员函数来调用“find”
【发布时间】:2021-05-26 13:52:17
【问题描述】:

当我尝试对 map 数据类型使用 find 函数时出现以下错误,而不是我所缺少的

错误

Line 20: Char 29: error: no matching member function for call to 'find'
                auto it = b.find(s[i]);
                          ~~^~~~
#include<map>
#include<vector>
#include<string>
class Solution {
public:
    bool isValid(string s) {
       int l = s.length();
    map<string,string> b;
        b["("] = ")";
        b["{"] = "}";
        b["["] = "]";

        vector<string> br;
        if(l%2 == 1)
            return false;
        else {
            for (int i=0;i<l;i++){
                auto it = b.find(s[i]);  \\ line where error is pointed 
                if(it != b.end() && br.size()==0){
                    return false;   
                }
                else if(it != b.end() && br.size()>0){
                    if(br.rbegin() == s[i]){
                        br.pop_back();
                    }

【问题讨论】:

  • s[i]charfind() 包含字符串的映射需要一个字符串
  • if(br.rbegin() == s[i]) 也不会按照你的想法去做,或者更确切地说它甚至不会编译。由于拼写错误(或多个拼写错误),我投票关闭。
  • 与 Python 不同,其中 'a'"a" 是同一个东西,单个字符 ('a') 与 C++ 中的单字符字符串 ("a") 不同。看起来你实际上想要一个map&lt;char, char&gt;

标签: c++ string algorithm dictionary find


【解决方案1】:

std::map&lt;std::string, std::string&gt;类的成员函数find的参数类型为const std::string &amp;。 但是,您使用的是 char 类型的参数,并且没有从 char 类型到 std::string 类型的隐式转换。

auto it = b.find(s[i]);

所以你需要将参数显式转换为std::string类型,或者提供一个可以隐式转换为std::string类型的对象。

例如,在上述调用之前,您可以声明一个字符数组,如

const char item[] = { s[i], '\0' };

然后写

auto it = b.find( item );

或者没有辅助字符数组你可以写

auto it = b.find( std::string ( 1, s[i]) );

在任何情况下,您都不清楚为什么要使用类型 std::map&lt;std::string, std::string&gt; 而不是 std::map&lt;char, char&gt;

注意你的代码还有其他错误。

例如在这个语句中

if(br.rbegin() == s[i]){

尝试将迭代器与 char 类型的对象进行比较。

也许你的意思是一个类型的向量

vector<char> br;

而不是类型的向量

vector<string> br;

在这种情况下,您可以编写上面显示的 if 语句,如

if( *br.rbegin() == s[i]){

【讨论】:

  • 嘿,我最初使用的是 map 但是当我尝试使用 find 方法对由字符串 's' 中的键索引的地图时,它显示了不同的错误,所以我更改了地图类型.感谢@VladfromMoscow 的初始修复
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
相关资源
最近更新 更多