关于 stl map 的 []操作符问题

本文详细解析了STL map中使用[]操作符时的行为特点,包括当键不存在时自动插入新元素并初始化的过程,以及为了支持这一行为,类需要实现的几个必要成员函数:无参构造函数、赋值运算符和拷贝构造函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

stl 文档中是如下描述:

Access element
If  k matches the key of an element in the container, the function returns a reference to its mapped value.

I f k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the  container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).
注意斜体字部分,也就是说,如果你的对象想保存在 map 中并且要用到[] 那么你的类起码要实现以下几个函数:无参数的构造函数   --- 对应元素不存在时 map 自行创建。operator =          ----- 用于  通过 [] 操作符来赋值拷贝构造函数         ---- 可能要用到,没具体研究,反正实现了总比不实现要好。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值