In this article, we will discuss different ways to print the last element of vector in C++.

Technique 1: Using vector::back() function

In C++, the vector class provides a function back(). It returns a reference of the last element of vector. But if the vector is empty, then it can cause the segmentation fault. We can call it to access the last element of vector, and then print it. Let’s see an example,

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    // Vector of integers
    vector<int> numbers {11, 12, 13, 14, 15, 16};

    // Get last element of vector
    int lastElem = numbers.back();

    // print last element of vector
    cout << lastElem << endl;

    return 0;
}

Output:

16

It printed the last element of vector.

Technique 2: Using subscript operator ( [] )

In C++, indexing starts from 0. So, the index position of the last element of vector is N-1, where N is the size of vector. Therefore, we can pass N-1 in the subscript operator of vector, to access the last element of vector. But if the vector is empty, then it can cause the segmentation fault. Let’s see an example, where we will access the last element of vector, and print it.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    // Vector of integers
    vector<int> numbers {11, 12, 13, 14, 15, 16};

    // Get number of elements in vector
    size_t len = numbers.size();

    // Get last element of vector
    int lastElem = numbers[len-1];

    // print last element of vector
    cout << lastElem << endl;

    return 0;
}

Output:

16

It printed the last element of vector.

Technique 3: Using vector::at() function

In C++, the vector class provides a function at(). It accepts an index position as argument, and returns a reference to the element at that index position. We can use it to access the last element of vector. For that we need to pass LEN-1 to the at() function, where LEN is the size of vector. Let’s see an example,

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    // Vector of integers
    vector<int> numbers {11, 12, 13, 14, 15, 16};

    // Get number of elements in vector
    size_t len = numbers.size();

    // Get last element of vector
    int lastElem = numbers.at(len-1);

    // print last element of vector
    cout << lastElem << endl;

    return 0;
}

Output:

16

It printed the last element of vector.

Important Point : The at() function will throws std::out_of_range exception if vector is empty.

Summary

We learned about three different ways to print the last element of vector in C++.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.