What is the vector.back() function in C++?
In this shot, we will learn about the vector::back() function in C++.
Introduction
The vector::back() function is available in the <vector> header file and returns a reference to the last element in the vector.
If we call the back() function on a vector that contains no elements, then we will get a “Segmentation Fault Error.”
Syntax
The syntax of the vector::back() function is given below:
reference back();
Parameters
The vector::back() function does not accept any parameters.
Return value
vector::back() returns a reference that points to the last element of the vector.
Code
Let’s have a look at the code.
#include <iostream>#include <vector>using namespace std;int main(){vector<int> vec;// cout << " The last element of an empty vector is: " << vec.back();vec.push_back(3);vec.push_back(4);vec.push_back(5);vec.push_back(6);vec.push_back(2);cout << " The last element of the vector is: " << vec.back();return 0;}
Explanation
-
In line 1, we include the C++ standard header file for the input-output stream (
iostream), which is used to read and write from streams. -
In line 2, we include the header file for C++ standard
vector, which includes all the functions and operations related to the vector container. -
In line 3, we use the standard (
std) namespace, which means that we use all the things within thestdnamespace. -
In line 7, we declare the integer type vector container named
vec. -
In line 9, we call the
back()function on an empty vector. If we uncomment the line, then we will get a “Segmentation Fault Error” because there is no element in the vector. -
In lines 11 to 15, we push back the different elements to the vector container
vec. -
In line 17, we print the result of the function
back(), which returns the last element of the vector container. In this example, is the last element, so the output is .
In this way, we can easily get the last element present in the vector.