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(10);//reserve只是用来预分配空间的,但要访问的话还是要压入数据或者执行resize,也就是初始化要用到的数据
    for(int i=0; i<7; i++)
    {
        v.push_back(i); //在V的尾部加入7个数据
    }

    try 
    {
        int iVal1 = v[7];
        // not bounds checked - will not throw

        int iVal2 = v.at(7);
        // bounds checked - will throw if out of range
    }
    catch(const exception& e)
    {
        cout << e.what();
    }
}

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

原文地址:https://www.cnblogs.com/chechen/p/9275721.html