介绍 std::vector 的 operator[]

介绍

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[]不同,此运算符从不向容器中插入新元素。通过此运算符访问不存在的元素是未定义的行为。

介绍 std::vector 的 operator[]_第1张图片

测试

#include
#include
#include
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

你可能感兴趣的:(C/C++,STL,c++,开发语言)