C++ map容器在const修饰下将无法使用“[]“来获取键值

编写程序时无意中发现使用const修饰的map容器变量无法使用重载的[]运算符来获取相应的键值,于是编写测试用例进行验证,如下

#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
	map<int, string> test;
	// 可以
	test[16] = "hello";
	test[5] = "jack";
	test[100] = "fine";
	for (auto var : test)
		cout << var.first << ":" << var.second << endl;

	cout << test[100] << endl;

	map<string, int> test1;
	// 可以
	test1["hello"] = 100;
	test1["I'm"] = 20;
	test1["fine"] = 4;
	int tmp = test1["hello"];
	cout << tmp << endl;

	// const 就不能使用[]获取结果
	const map<string, int> anot = { {"jack", 2}, {"fun", 5} };
	tmp = anot["jack"];    // !!!此处报错,证明const修饰下的map无法使用[]
	return 0;
}

查阅资料后发现,

对于const的对象使用了非const的成员函数:std::map::[]本身不是const成员函数(操作符),对于不在map中的关键字,使用下标操作符会创建新的条目,改变了map

解决方法是使用at成员函数

tmp = anot.at("jack");    // 可以使用at成员方法来解决
  • 20
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值