介绍 std::map 的 operator[]

介绍

只要代码中使用了 std::map::operator[] 操作符就会 访问或插入指定的元素

std::map<Key,T,Compare,Allocator>::operator[]
----------------------------------------------
T& operator[]( const Key& key );   //(1)	
T& operator[]( Key&& key );        //(2)	(since C++11)

operator[]
access or insert specified element (public member function)
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

std::map::operator[] 返回对映射到与键等效的键的值的引用,如果该键不存在,则执行插入

测试

#include<stdio.h>
#include<string.h>
#include<map>
using namespace std;

int main(void)
{
  std::map<int, int> test;
  printf("----test.size()=%d\n", test.size());
  
  printf("----test[0]=%d\n", test[0]);
  printf("----test.size()=%d\n", test.size());
  printf("----test[2]=%d\n", test[2]);
  printf("----test.size()=%d\n", test.size());
  
  test.clear();
  printf("----clear\n");
  printf("----test.size()=%d\n", test.size());
  test[3] = 3;
  printf("----test.size()=%d\n", test.size());
  test.clear();
  printf("----test.size()=%d\n", test.size());

  return 0;
}

输出:

----test.size()=0
----test[0]=0
----test.size()=1
----test[2]=0
----test.size()=2
----clear
----test.size()=0
----test.size()=1
----test.size()=0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值