C++ STL 中的 array at() 函式
陣列是儲存在連續記憶體位置中具有相同資料型別的一系列元素。
在 c++ 標準庫 (STL) 中有許多方法來支援陣列的功能。其中一種是 array 的 at() 方法。
array at() 方法用於返回特定索引值處的元素的引用。
語法
編寫 array at() 函式的一般語法為
array_name.at(i);
引數
該函式接受一個引數,該引數是函式訪問的元素的索引。
返回
該函式返回在呼叫時傳遞其索引的元素。如果傳遞了任何無效的索引值,函式將丟擲 out_of_range 異常。
示例
演示 Array::At() 函式工作原理的程式 −
#include <bits/stdc++.h>
using namespace std;
int main(){
array<float, 4> arr = { 12.1, 67.3, 45.0, 89.1 };
cout << "The element at index 1 is " << arr.at(1) << endl;
return 0;
}輸出
The element at index 1 is 67.3
示例
當索引值大於陣列長度時說明錯誤的程式 −
#include <bits/stdc++.h>
using namespace std;
int main(){
array<float, 4> arr = { 12.1, 67.3, 45.0, 89.1 };
cout << "The element at index 1 is " << arr.at(8) << endl;
return 0;
}輸出
terminate called after throwing an instance of 'std::out_of_range' what(): array::at: __n (which is 8) >= _Nm (which is 4) The element at index 1 is Aborted
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP