C++ Standard Library C++ STL Library

C++ <vector> - back() Function



The C++ vector::back function returns a reference to the last element of the vector. Please note that, Unlike the vector::rbegin function, which returns the reverse iterator pointing to the last element, it returns the a direct reference to the same element of the vector.

Syntax

reference back();
const_reference back() const;
reference back();
const_reference back() const;

Parameters

No parameter is required.

Return Value

A reference to the last element of the vector.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::back function is used to access the last element of the vector Vec.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> Vec{10, 20, 30, 40, 50};

  cout<<"The last element of Vec is: ";
  cout<<Vec.back();

  cout<<"\n\n100 is added to the last element of the Vector.\n";
  Vec[4] = Vec[4] + 100;

  cout<<"Now, The last element of Vec is: ";
  cout<<Vec.back();  
  return 0;
}

The output of the above code will be:

The last element of Vec is: 50

100 is added to the last element of the Vector.
Now, The last element of Vec is: 150

❮ C++ <vector> Library