std::span<T,Extent>::operator[]

From cppreference.com
< cpp‎ | container‎ | span
 
 
 
std::span
Member functions
(C++20)
Element access
(C++20)
span::operator[]
(C++20)
(C++20)
Iterators
(C++20)(C++23)
(C++20)(C++23)
Observers
(C++20)
Subviews
(C++20)
Non-member functions
Non-member constant
Deduction guides(C++20)
 
constexpr reference operator[]( size_type idx ) const;
(since C++20)

Returns a reference to the idxth element of the sequence. The behavior is undefined if idx is out of range (i.e., if it is greater than or equal to size()).

Parameters

idx - the index of the element to access

Return value

A reference to the idxth element of the sequence, i.e., data()[idx].

Exceptions

Throws nothing.

Example

#include <cstddef>
#include <iostream>
#include <span>
#include <utility>
 
void reverse(std::span<int> span)
{
    for (std::size_t i = 0, j = std::size(span); i < j; ++i)
    {
        --j;
        std::swap(span[i], span[j]);
    }
}
 
void print(std::span<const int> const span)
{
    for (int element : span)
        std::cout << element << ' ';
    std::cout << '\n';
}
 
int main()
{
    int data[]{1, 2, 3, 4, 5};
    print(data);
    reverse(data);
    print(data);
}

Output:

1 2 3 4 5
5 4 3 2 1

See also

(C++20)
returns a pointer to the beginning of the sequence of elements
(public member function)
(C++20)
returns the number of elements in the sequence
(public member function)