错误:与“ operator []”不匹配操作数类型为“ std :: map <std :: __ cxx11 :: basic_string <char>,int>”和“ char”

问题描述

我想测试增量++是否对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;
}

然后Ì获得标题错误:

map['1'] = 0;

我不明白为什么

解决方法

在C ++中,'1'是一个字符,而不是字符串文字,并且您的映射具有一个密钥std::string,该密钥不是同一类型。这就是std::map::operator[]给您编译器错误的原因,它是不匹配类型。

您需要""来提及它是字符串文字。

map["1"] = 0;

另外,请阅读:

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...