vector at()函数比 []运算符操作安全

时间:2023-03-10 03:23:53
vector at()函数比 []运算符操作安全

转载:https://blog.csdn.net/chenjiayi_yun/article/details/18507659

[]操作符的源码

reference

operator[](size_type __n)

{ return *(begin() + __n); }

at函数的源码

reference
      at(size_type __n)
      {
_M_range_check(__n);
return (*this)[__n]; 
      }

可以看出来at函数主要是多做个超出范围的 检查。

void
      _M_range_check(size_type __n) const
      {
if (__n >= this->size())
 __throw_out_of_range(__N("vector::_M_range_check"));
      }

以下是一个小函数,可以用来检查下:

void Testvector1()
{
vector<int> v;
v.reserve();//reserve只是用来预分配空间的,但要访问的话还是要压入数据或者执行resize,也就是初始化要用到的数据
for(int i=; i<; i++)
{
v.push_back(i); //在V的尾部加入7个数据
} try
{
int iVal1 = v[];
// not bounds checked - will not throw int iVal2 = v.at();
// bounds checked - will throw if out of range
}
catch(const exception& e)
{
cout << e.what();
}
}

使用[]云算法结果输出结果:

vector at()函数比 []运算符操作安全