Search code examples
c++algorithmc++11stdmapstdstring

error: no match for ‘operator[]’ (operand types are ‘std::map<std::__cxx11::basic_string<char>, int>’ and ‘char’)


I wanted to test if the increment ++ works for the std::map :

#include <bits/stdc++.h>

using namespace std;
int main() 
{
   map<string, int> map;;
   map['1'] = 0;
   map['1']++;
   cout << map['1'] << endl;
   return 0;
}

And Ì get the error of the title for :

map['1'] = 0;

I do not understand why


Solution

  • In C++ '1' is a character, not a string literal, and your map has a key std::string, which is not same types. That is why the std::map::operator[] gave you the compiler error, it is mismatch type.

    You need "" for mentioning it is a string literal.

    map["1"] = 0;
    

    Also, have a read: