Skip to main content

std::vector back() method

// prism-push-types:reference,const_reference
// Non const version
constexpr reference back();

// Const version
constexpr const_reference back() const;

Returns a reference

to the last element in the container.

Undefined Behavior

Calling back() on an empty container is undefined behavior

.

Parameters

(none)

Return value

Reference to the last element.

Complexity

Constant - O(1).

Notes

For a container c, the expression c.back() is equivalent to *std::prev(c.end()) and c[c.size() - 1].

Example

Main.cpp
#include <array>
#include <iostream>

int main()
{
std::vector<char> letters {'o', 'm', 'g', 'w', 't', 'f'};

if (!letters.empty()) {
std::cout << "The last character is '" << letters.back() << "'.\n";
}
}
Output
The last character is 'f'.
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::vector back() method

// prism-push-types:reference,const_reference
// Non const version
constexpr reference back();

// Const version
constexpr const_reference back() const;

Returns a reference

to the last element in the container.

Undefined Behavior

Calling back() on an empty container is undefined behavior

.

Parameters

(none)

Return value

Reference to the last element.

Complexity

Constant - O(1).

Notes

For a container c, the expression c.back() is equivalent to *std::prev(c.end()) and c[c.size() - 1].

Example

Main.cpp
#include <array>
#include <iostream>

int main()
{
std::vector<char> letters {'o', 'm', 'g', 'w', 't', 'f'};

if (!letters.empty()) {
std::cout << "The last character is '" << letters.back() << "'.\n";
}
}
Output
The last character is 'f'.
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.