Chakrakeerthi Reddy
Chakrakeerthi Reddy

Reputation: 3

C++ map no matching member function for call to 'find' when used for a string

I'm getting below error when I try using find function for map<string,string> datatype, not what I'm missing

error

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

Upvotes: 0

Views: 5570

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

The parameter type of the member function find of the class std::map<std::string, std::string> is const std::string &. However you are using an argument of the type char and there is no implicit conversion from the type char to the type std::string.

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

So you need to convert explicitly the argument to the type std::string or provide an object of a type that can be implicitly converted to the type std::string.

For example before the call above you could declare a character array like

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

and then write

auto it = b.find( item );

Or without the auxiliary character array you could just write

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

In any case it is unclear why you are using the type std::map<std::string, std::string> instead of std::map<char, char>.

Pay attention to that your code has other errors.

For example in this statement

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

there is an attempt to compare an iterator with an object of the type char.

Maybe you mean a vector of the type

vector<char> br;

instead of the vector of the type

vector<string> br;

In this case you could write the above shown if statement like

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

Upvotes: 3

Related Questions