C++ Array::at() 函式



C++ 的std::array::at()函式提供了一種訪問陣列元素並進行邊界檢查的方法。它返回對陣列中指定位置元素的引用。

與不執行邊界檢查的運算子[]不同,如果提供的索引超出有效範圍(0 到 size-1),at() 會丟擲out_of_range異常。

語法

以下是 std::array::at() 函式的語法。

reference at ( size_type n );
const_reference at ( size_type n ) const;

引數

  • N − 表示陣列中元素的位置。

返回值

此函式返回陣列中指定位置的元素。

異常

如果 N 的值不是有效的陣列索引,則此函式會丟擲 out_of_range 異常。

時間複雜度

常數,即 O(1)

示例 1

在下面的示例中,步驟 1 列印陣列內容而不會出現異常。步驟 2 演示了使用 try-catch 塊進行異常處理。

#include <iostream>
#include <array>
#include <stdexcept>
using namespace std;
int main(void) {
   array < int, 5 > arr = {10, 20, 30, 40, 50};
   size_t i;
   for (i = 0; i < 5; ++i)
      cout << arr.at(i) << " ";
   cout << endl;
   try {
      arr.at(10);
   } catch (out_of_range e) {
      cout << "out_of_range expcepiton caught for " << e.what() << endl;
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

10 20 30 40 50 
out_of_range expcepiton caught for array::at: __n (which is 10) >= _Nm (which is 5)

示例 2

考慮以下示例,我們將使用 at() 函式獲取整數的索引位置。

#include <iostream>
#include <array>
using namespace std;
int main() {
   array < int, 10 > arr = {9, 12, 15, 18, 21, 24, 27, 30, 33, 36};
   cout << "The location of the element at index 6 = " << arr.at(6) << endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

The location of the element at index 6 = 27

示例 3

以下示例演示了使用 at() 函式查詢陣列長度小於索引位置的情況。

#include <iostream>
#include <array>
using namespace std;
int main() {
   array < int, 10 > arr = {9, 12, 15, 18, 21, 24, 27, 30, 33, 36};
   cout << "The location of the element at index 20 = " << arr.at(20) << endl;
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出:

terminate called after throwing an instance of 'std::out_of_range'
  what():  array::at: __n (which is 20) >= _Nm (which is 10)
Aborted
array.htm
廣告