Namespaces
Variants

std::span<T,Extent>:: back

From cppreference.net
constexpr reference back ( ) const ;
(since C++20)

Returns a reference to the last element in the span.

If empty() is true , the behavior is undefined.

(until C++26)

If empty() is true :

  • If the implementation is hardened , a contract violation occurs. Moreover, if the contract-violation handler returns under “observe” evaluation semantic, the behavior is undefined.
  • If the implementation is not hardened, the behavior is undefined.
(since C++26)

Contents

Return value

A reference to the back element.

Complexity

Constant.

Notes

For a span c , the expression c. back ( ) is equivalent to * ( c. end ( ) - 1 ) .

Example

#include <iostream>
#include <span>
void print_forward(const std::span<const int> span)
{
    for (auto n{span.size()}; n != 0; --n)
        std::cout << span.last(n).front() << ' ';
    std::cout << '\n';
}
void print_backward(const std::span<const int> 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

access the first element
(public member function)