C++ vector::back() 函数



C++ vector::back() 函数用于返回向量最后一个元素的引用。如果在空向量上使用 back() 函数,则会遇到“段错误”。back() 函数的时间复杂度为常数。

用于存储数据的动态数组称为向量。与仅存储顺序数据且本质上是静态的数组相比,向量提供了更大的灵活性。当向向量中添加或删除元素时,向量的大小可以自动调整。

语法

以下是 C++ vector::back() 函数的语法:

reference back();const_reference back() const;

参数

它不包含任何参数。

示例 1

让我们考虑以下示例,我们将使用 back() 函数并检索输出。

#include<iostream>
#include<vector>
using namespace std;

int main(){
   vector<string>  courses{"HTML","JAVA","SQL"};
   cout<<courses.back();
   return 0;
}

输出

当我们编译并运行上述程序时,它将产生以下结果:

SQL

示例 2

在以下示例中,我们将运行循环并应用 back() 函数并检索输出。

#include<iostream>
#include<vector>
using namespace std;

int main(){
   vector<int> a;
   for (int i = 0; i <= 9; i++)
      a.push_back(i * 10);
   cout << "\nResult :  " << a.back();
   return 0;
}

输出

运行上述程序后,它将产生以下结果:

Result :  90

示例 3

以下是另一种情况,我们将使用 back() 函数获取最后一个元素。

#include <iostream>
#include <vector>
using namespace std;

int main(){
   vector<int> tutorial;
   tutorial.push_back(12);
   tutorial.push_back(23);
   tutorial.push_back(34);
   tutorial.push_back(45);
   cout << " The last element is: " << tutorial.back();
   return 0;
}

输出

运行上述程序后,它将产生以下结果:

The last element is: 45

示例 4

让我们考虑以下示例,它在对空向量使用 back() 函数时会抛出错误。

#include <iostream>
#include <vector>
using namespace std;

int main(){
   vector<int> tutorial = {};
   cout << tutorial.back() << endl;
   return 0;
}

输出

当我们执行上述程序时,它将产生以下结果:

Segmentation fault
广告

© . All rights reserved.