std::vector::back(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

okay so bestie, welcome to std::vector::back(3) β€” this page lives in the C++ Standard Libary manual, and we are about to get that last-element situation handled. πŸ’…βœ¨

NAME πŸŽ€

std::vector::back β€” std::vector::back. that's the name, and honestly the NAME section is giving minimal effort, but we respect it. 🫢

Synopsis πŸ“œ

Two overloads, and both are constexpr since C++20:

reference back();             (1) (constexpr since C++20)
const_reference back() const; (2) (constexpr since C++20)

Returns a reference to the last element in the container. slay.

⚠️ Calling back on an empty container causes undefined behavior. not a cute vibe, not a drill, bestie πŸ˜­πŸ’€

Parameters 🫢

(none) β€” literally none. no parameters, no extra drama.

Return value πŸ’–

Reference to the last element. periodt.

Complexity ⚑

Constant. iconic behavior, no cap.

Notes 🧚

For a non-empty container c, the expression c.back() is equivalent to *std::prev(c.end()). iykyk ✨

Example 🌸

This lil code uses back to display the last element of a std::vector<char>:

// Run this code

#include <vector>
#include <iostream>

int main()
{
    std::vector<char> letters{'a', 'b', 'c', 'd', 'e', 'f'};

    if (!letters.empty())
        std::cout << "The last character is '" << letters.back() <<
       "'.\n";
}

Output:

The last character is 'f'.

See also πŸ‘‘

  • front β€” access the first element (public member function).

okay bye bestie πŸ«ΆπŸ’– β€” source: http://cppreference.com, version/date: 2024.06.10, page: std::vector::back(3). mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from