Open In App

Vector back() in C++ STL

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the vector back() is a built-in function used to retrieve the last element of the vector. It provides a reference to the last element which allows us to read or modify it directly.

Let’s take a quick look at a simple example that illustrates the vector back() method:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
  	vector<int> v = {5, 10, 15, 20};

  	// Accessing the last element of vector v
    cout << v.back();
  
    return 0;
}

Output
20

This article covers the syntax, usage, and common examples about the vector back() method in C++ STL:

Syntax of Vector back()

The vector back() is a member method of std::vector class defined inside <vector> header file.

v.back();

Parameters:

  • This function does not take any parameters.

Return Value:

  • Returns the reference to the last element of the vector container if present.
  • If the vector is empty, then the behaviour is undefined.

Examples of Vector back()

The below examples illustrate how to use vector back for different purposes and in different situation:

Modify the Last Element of the Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {5, 10, 15, 20};

    // Modify the last element
    v.back() = 50;

    for (int i : v)
        cout << i << " ";
    return 0;
}

Output
5 10 15 50 

Behaviour of Vector back() with Empty Vectors

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v;

  	// Checking whether a vector is empty before using
  	// vector back() method
    if (!v.empty()) {
        cout << v.back();
    } else {
        cout << "Vector is empty!";
    }

    return 0;
}

Output
Vector is empty!

Explanation: Calling back() on an empty vector causes undefined behaviour. To prevent this, always check if the vector is not empty.

Difference Between Vector back() and end()

The vector back() and vector end() can both be used in to access the last element of the vector, but they have some differences:

FeatureVector back()Vector end()
PurposeReturns a reference to the last element of the vector.Returns an iterator pointing to one past the last element.
Return TypeReference (T&) or constant reference (const T&).vector<T>::iterator type.
UsageOnly used for direct access to the last element.Can be used for iteration and access.
Syntaxv.back();*(v.end() - 1);

In Short,

  • Use back() for quick, direct access to the last element.
  • Use end() when working with iterators or algorithms.

Next Article
Practice Tags :

Similar Reads