C++ 中向量的最後一個元素(訪問和更新)


在本文中,我們將討論在 C++ 中訪問和更新向量最後一個元素的方法。

什麼是向量模板?

向量是其大小動態變化的順序容器。容器是一個儲存相同型別資料的物件。順序容器嚴格按線性順序儲存元素。

向量容器將元素儲存在連續的記憶體位置,並允許使用下標運算子 [] 直接訪問任何元素。與陣列不同,向量的尺寸是動態的。向量的儲存由系統自動處理。

向量的定義

Template <class T, class Alloc = allocator<T>> class vector;

向量的引數

該函式接受以下引數:

  • T - 這是包含的元素的型別。

  • Alloc - 這是分配器物件的型別。

我們如何訪問向量的最後一個元素?

要訪問向量的最後一個元素,我們可以使用兩種方法

示例

使用 back() 函式

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   vector<int> vec = {11, 22, 33, 44, 55};
   cout<<"Elements in the vector before updating: ";
   for(auto i = vec.begin(); i!= vec.end(); ++i){
      cout << *i << " ";
   }
   // call back() for fetching last element
   cout<<"\nLast element in vector is: "<<vec.back();
   vec.back() = 66;
   cout<<"\nElements in the vector before updating: ";
   for(auto i = vec.begin(); i!= vec.end(); ++i){
      cout << *i << " ";
   }
   return 0;
}

輸出

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

Elements in the vector before updating: 11 22 33 44 55
Last element in vector is: 55
Elements in the vector before updating: 11 22 33 44 66

示例

使用 size() 函式

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   vector<int> vec = {11, 22, 33, 44, 55};
   cout<<"Elements in the vector before updating: ";
   for(auto i = vec.begin(); i!= vec.end(); ++i){
      cout << *i << " ";
   }
   // call size() for fetching last element
   int last = vec.size();
   cout<<"\nLast element in vector is: "<<vec[last-1];
   vec[last-1] = 66;
   cout<<"\nElements in the vector before updating: ";
   for(auto i = vec.begin(); i!= vec.end(); ++i){
      cout << *i <<" ";
   }
   return 0;
}

輸出

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

Elements in the vector before updating: 11 22 33 44 55
Last element in vector is: 55
Elements in the vector before updating: 11 22 33 44 66

更新於: 2020-04-22

621 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告