在本文中,我们将讨论在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