std::span::back(3)

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

πŸ’… std::span::back(3) πŸ’…

okay so this is the std::span::back(3) page from the C++ Standard Libary manual β€” yes, bestie, "Libary" is literally how it's spelled up in there, and we're keeping it. It's the whole vibe guide to grabbing a reference to the last element in a span. No cap, it's short, it's iconic, and it's giving "one job, do it flawlessly." πŸ¦‹

✨ NAME ✨

  • std::span::back - std::span::back

That's it. That's the name. Main character energy from the jump. πŸ’…

🌸 Synopsis 🌸

constexpr reference back() const;  (since C++20)

Returns a reference to the last element in the span. Periodt.

Calling back on an empty span results in undefined behavior. Like, actual UB, bestie β€” not a cute little empty-span moment. Do not do it. πŸ’€

πŸŽ€ Parameters πŸŽ€

  • (none) β€” literally no parameters, she takes no arguments and still serves.

🫢 Return value 🫢

A reference to the back element. That's the whole return value. Slay. ✨

⚑ Complexity ⚑

Constant. That's it. Constant energy only. 🫢

πŸ“ Notes πŸ“

For a span c, the expression c.back() is equivalent to *(c.end() - 1). iykyk β€” that's the little secret handshake.

🎬 Example 🎬

// Run this code

#include <iostream>
#include <span>

void print_forward(std::span<const int> const span)
{
    for (auto n{span.size()}; n != 0; --n)
        std::cout << span.last(n).front() << ' ';
    std::cout << '\n';
}

void print_backward(std::span<const int> const span)
{
    for (auto n{span.size()}; n != 0; --n)
        std::cout << span.first(n).back() << ' ';
    std::cout << '\n';
}

int main()
{
    constexpr int numbers[]{0, 1, 2, 3, 4};
    print_forward(numbers);
    print_backward(numbers);
}

πŸ–₯️ Output:

0 1 2 3 4
4 3 2 1 0

πŸ‘€ See also πŸ‘€

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

cute sign-off: this page came from http://cppreference.com, its date is 2024.06.10, and the page is std::span::back(3). mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from