介绍
只要代码中使用了 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