介绍
std::vector::operator[]
操作符只能 访问指定的元素
std::vector<T,Allocator>::operator[]
-------------------------------------
reference operator[]( size_type pos ); //(until C++20)
constexpr reference operator[]( size_type pos ); //(since C++20)
const_reference operator[]( size_type pos ) const; //(until C++20)
constexpr const_reference operator[]( size_type pos ) const; //(since C++20)
operator[]
access specified element
(public member function)
Returns a reference to the element at specified location pos. No bounds checking is performed.
std::vector::operator[]
返回对指定位置的元素的引用。不执行边界检查。
与std::map::operator[]
不同,此运算符从不向容器中插入新元素。通过此运算符访问不存在的元素是未定义的行为。
测试
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
int main(void)
{
std::vector<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]=1668509029
----test.size()=0
----test[2]=0
----test.size()=0
----clear
----test.size()=0
----test.size()=0
----test.size()=0