A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/vector-back-in-cpp-stl/ below:

Vector back() in C++ STL

Vector back() in C++ STL

Last Updated : 23 Jul, 2025

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;
}

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:

Return Value:

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;
}
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;
}

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:

Feature Vector back() Vector end() Purpose Returns a reference to the last element of the vector. Returns an iterator pointing to one past the last element. Return Type Reference (T&) or constant reference (const T&). vector<T>::iterator type. Usage Only used for direct access to the last element. Can be used for iteration and access. Syntax v.back(); *(v.end() - 1);

In Short,



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4