C++ vector::at() 函式



C++ vector::at() 函式提供對位於指定索引處的元素的引用。如果位置或索引號超出範圍且不在向量中,則 at() 函式會丟擲超出範圍異常。at() 函式的時間複雜度是常數。

在 C++ 中,向量是表示陣列的順序容器,可以在執行時改變其大小。它們像陣列一樣有效地使用連續的儲存位置來儲存其元素,因此也可以使用其元素的常規指標上的偏移量來訪問其元素。

語法

以下是 C++ vector::at() 函式的語法:

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

引數

n − 表示容器中元素的位置。如果大於或等於向量的size,則丟擲異常。

示例 1

讓我們考慮以下示例,我們將使用 at() 函式並檢索輸出。

#include<iostream>
#include<vector>
using namespace std;

int main(){
   vector<int> tutorial{11,22,33,44};
   for(int i=1; i<tutorial.size(); i++)
      cout<<tutorial.at(i);
   return 0;
}

輸出

當我們編譯並執行上述程式時,將產生以下結果:

223344

示例 2

在以下示例中,我們將讀取向量中的所有元素。

#include<iostream>
#include<vector>
using namespace std;

int main(){
   vector tutorial = {"TutorialsPoint","TP","Tutorix"};
   for(int i=0; i<tutorial.size(); i++){
      cout<< tutorial.at(i) << "\n";
   }
   cout<< "\n";
   return 0;
}

輸出

執行上述程式後,將產生以下結果:

TutorialsPoint
TP
Tutorix

示例 3

考慮以下示例,我們將計算向量值的差值。

#include <iostream>
#include <vector>
using namespace std;

int main (){
   vector<int>tutorial {2,4,6,8,1,3,5,7};
   int sub = 0;
   cout<< "Values:\n";
   for (int i=0; i<tutorial.size(); i++)
      cout<< ' ' << tutorial.at(i);
   cout<< '\n';
   for (int i=0; i<tutorial.size(); i++)
      sub -= tutorial.at(i);
   cout<< "Subtraction of all the values is : " << sub << "\n";
   return 0;
}

輸出

讓我們編譯並執行上述程式,它將產生以下結果:

Values:
 2 4 6 8 1 3 5 7
Subtraction of all the values is : -36

示例 4

以下是另一種情況,我們將使用 at() 函式更改向量值。

#include <iostream>
#include <vector>
using namespace std;

int main(){
   vector<int> tutorial {22,88,66,55,44};
   cout << "Declared Vector: ";
   for (const int& i : tutorial) {
      cout << i << "  ";
   }
   tutorial.at(2) = 77;
   tutorial.at(0) = 99;
   cout << "\nModified Vector: ";
   for (const int& i : tutorial) {
      cout << i << "  ";
   }
   return 0;
}

輸出

執行上述程式後,將產生以下結果:

Declared Vector: 22  88  66  55  44  
Modified Vector: 99  88  77  55  44

示例 5

讓我們考慮以下示例,它在傳遞 'age.at(3) = 5'(超出已宣告向量範圍)時會丟擲錯誤。

#include <iostream>
#include <vector>
using namespace std;

int main(){
   vector<int> age = {2,3,4};
   age.at(3) = 5;
   for(int i = 0; i < age.size() ; i++) {
      cout << "age[" << i << "] = " << age.at(i) << endl;
   }
   return 0;
}

輸出

執行上述程式時,將產生以下結果:

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 3) >= this->size() (which is 3)
廣告