std::span::operator[](3)

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

✨ NAME ✨

Okay bestie, this is the page for std::span::operator[] β€” title and section number and all: std::span::operator[](3) β€” from the C++ Standard Libary. Yes, β€œLibary” is literally how the manual name is spelled on this page, and I am not fixing it. πŸ’…

std::span::operator[] - std::span::operator[]


🌸 SYNOPSIS 🌸

constexpr reference operator[]( size_type idx ) const;  (since C++20)

Returns a reference to the idx-th element of the sequence. Cute and simple. 🫢

🚨 UB ALERT: the behavior is undefined if idx is out of range (i.e., if it is greater than or equal to size()). Not a vibe, no cap, do not do this. 😭

πŸŽ€ PARAMETERS πŸŽ€

  • idx β€” the index of the element to access

πŸ’– RETURN VALUE πŸ’–

A reference to the idx-th element of the sequence, i.e., data()[idx]. That’s the whole gift. 🎁

😭 EXCEPTIONS 😭

Throws nothing. Literally nothing. No exception drama here. Periodt.

🧚 EXAMPLE 🧚

// Run this code πŸ‘‡

#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 πŸ‘€

  • at β€” access specified element with bounds checking (public member function) (C++26)
  • data β€” direct access to the underlying contiguous storage (public member function)
  • size β€” returns the number of elements (public member function)
  • as_bytes β€” converts a span into a view of its underlying bytes
  • as_writable_bytes β€” (function template) (C++20)

Source/version/date sign-off, because the footer is iconic too: this page is from http://cppreference.com, version 2024.06.10, and it’s std::span::operator[](3). Bye bestie β€” go access some elements, but keep idx in range πŸ‘‘βœ¨πŸ’–

πŸ“¦ where this page comes from