Home »
C++ STL
vector::back() function with example in C++ STL
C++ STL vector::back() function: Here, we are going to learn about the back() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 15, 2019
C++ vector::back() function
vector::back() is a library function of "vector" header, it is used to access the last element from the vector, it returns a reference to the last element of the vector.
Note: To use vector, include <vector> header.
Syntax
Syntax of vector::back() function
vector::back();
Parameter(s)
none – It accepts nothing.
Return value
reference – It returns a reference to the last element of vector.
Sample Input and Output
Input:
vector<int> vector1{ 1, 2, 3, 4, 5 };
Function call:
cout << vector1.back() << endl;
Output:
5
C++ program to demonstrate example of vector::back() function
//C++ STL program to demonstrate example of
//vector::back() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1{ 10, 20, 30, 40, 50 };
//accessing last element
//using vector::back() function
cout << "last element is: " << v1.back() << endl;
//changing last element
v1.at(v1.size() - 1) = 100;
cout << "now, last element is: " << v1.back() << endl;
//changing last element
//using push_back()
v1.push_back(200);
cout << "now, last element is: " << v1.back() << endl;
return 0;
}
Output
last element is: 50
now, last element is: 100
now, last element is: 200
Reference: C++ vector::back()