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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP