基本信息
文件名称:获取数组中的最后一个元素的C++程序.docx
文件大小:16.47 KB
总页数:6 页
更新时间:2025-06-24
总字数:约3.55千字
文档摘要

获取数组中的最后一个元素的C++程序

intmAIn(){

intA[Z]={57,10,14,19,86,52,32,14,76,65,32,14};

intn=12;

coutGivenArray:

displayArr(A,n);

intlast=pickLastElement(A,n);

coutThelastelementofA:lastendl;

intB[Z]={98,12,10,23,45,74};

intm=6;

coutAnotherarray:

displayArr(B,m);

last=pickLastElement(B,m);

coutThelastelementofB:lastendl;

GivenArray:57,10,14,19,86,52,32,14,76,65,32,14,

ThelastelementofA:14

Anotherarray:98,12,10,23,45,74,

ThelastelementofB:74

使用指针和基地址

数组是基址(first)加上偏移量(indices)的位置地址。因此,可以使用指针来访问索引,而不使用方括号。要获取最后一个元素,可以使用数组的基址值。让我们看一下具体实现以获得更清晰的视图。

Example的中文翻译为:

#includeiostream

#defineZ50

usingnamespacestd;

voiddisplayArr(intarr[],intn){

for(inti=0;ii++){

coutarr[i],

coutendl;

intpickLastElement(intA[],intn){

intlast;

last=*(A+n-1);

returnlast;

intmain(){

intA[Z]={57,10,14,19,86,52,32,14,76,65,32,14};

intn=12;

coutGivenArray:

displayArr(A,n);

intlast=pickLastElement(A,n);

coutThelastelementofA:lastendl;

intB[Z]={98,12,10,23,45,74};

intm=6;

coutAnotherarray:

displayArr(B,m);

last=pickLastElement(B,m);

coutThelastelementofB:lastendl;

GivenArray:57,10,14,19,86,52,32,14,76,65,32,14,

ThelastelementofA:14

Anotherarray:98,12,10,23,45,74,

ThelastelementofB:74

这里A的值(用指针*A表示)表示A指向的地址的值。这是数组的基地址。

Vectors是动态数组,否则,整个东西与数组类似。在这里,要读取最后一个元素,我们只需要访问最后一个索引,即vector.size()-1。代码如下所示-

Example的中文翻译为:

#includeiostream

#includevector

#defineZ50

usingnamespacestd;

voiddisplayArr(vectorintv){

for(inti=0;iv.size();i++){

coutv[i],

coutendl;

intpickLastElement(vectorintA){

intlast;

last=A[A.size()-1];

returnlast;

intmain(){

vectorintA={57,10,14,19,86,52,32,14,76,65,32,14}