C++ 中 Vector 的最后一个元素(访问和更新)
c++server side programmingprogramming
本文将讨论在 C++ 中访问和更新 Vector 最后一个元素的方法。
什么是 Vector 模板?
Vector 是大小动态变化的序列容器。容器是一个对象,用于保存相同类型的数据。序列容器严格按照线性顺序存储元素。
Vector 容器将元素存储在连续的内存位置,并允许使用下标运算符 [] 直接访问任何元素。与数组不同,Vector 的大小是动态的。Vector 的存储是自动处理的。
Vector 的定义
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 << " "; } // 回调()以获取最后一个元素 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
示例
using size() function
#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 << " "; } // 调用 size() 获取最后一个元素 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