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();
    }
}

使用[]雲算法結果輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM