std::span::at(3)

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

🌸 std::span::at(3) 🌸

ok so bestie, we're in the C++ Standard Library today β€” this is std::span::at, and it's literally the safe-girl way to index into a span πŸ’…


✨ NAME ✨

std::span::at β€” and yes, the name is just std::span::at again, that's the whole vibe, no notes πŸŽ€


πŸ¦‹ SYNOPSIS πŸ¦‹

constexpr reference at( size_type pos ) const;  (since C++26)

ok so what it does: it hands you a reference to the element at the location you specified with pos, BUT β€” and this is the whole point β€” it does bounds checking. 🫢

and if pos is not within the range of the span? it throws an exception of type std::out_of_range. no cap, it will actually do that. 😭


πŸ’– PARAMETERS πŸ’–

  • pos β€” the position of the element you wanna get back. that's it, that's the parameter 🌸

⭐ RETURN VALUE ⭐

a reference to the element you asked for, i.e. *(data() + pos). icon behavior honestly πŸ‘‘


πŸ”₯ EXCEPTIONS πŸ”₯

  • std::out_of_range if pos >= size(). periodt. πŸ’€

🧚 COMPLEXITY 🧚

Constant. as in O(1). as in she's fast. ⚑


πŸ’œ NOTES πŸ’œ

there's a feature-test macro for this one, so you can vibe check whether your implementation has it:

  • Feature-test macro: __cpp_lib_span
  • Value: 202311L
  • Std: (C++26)
  • Feature: std::span::at

iykyk 🌈


πŸ“ EXAMPLE πŸ“

// Run this code

#include <iostream>
#include <span>
#include <stdexcept>

#ifdef __GNUG__
[[gnu::noinline]]
#endif
unsigned int runtime_six() // Emulate runtime input
{
    return 6u;
}

int main()
{
    int x[]{1, 2, 4, 5, 5, 6};
    std::span data(x);

    // Set element 1
    data.at(1) = 88;

    // Read element 2
    std::cout << "Element at index 2 has value " << data.at(2) << '\n';

    std::cout << "data size = " << data.size() << '\n';

    try
    {
        // Set element 6, where the index is determined at runtime
        data.at(runtime_six()) = 666;
    }
    catch (std::out_of_range const& exc)
    {
        std::cout << exc.what() << '\n';
    }

    // Print final values
    std::cout << "data:";
    for (int elem : data)
        std::cout << ' ' << elem;
    std::cout << '\n';
}

🌟 Possible output: 🌟

Element at index 2 has value 4
data size = 6
std::out_of_range: pos >= size()
data: 1 88 4 5 5 6

ngl the std::out_of_range: pos >= size() line is so satisfying to see trigger properly 😌 the catch block ate, fr fr.


πŸ‘‘ SEE ALSO πŸ‘‘

  • operator[] β€” access specified element (public member function)

like, the chaotic sibling who does NOT check bounds. choose wisely bestie πŸ™ˆ


quick reminder that std::span::at is only here since C++26, so if your compiler's being a hater about it, that's why πŸ’…

made with love on 2024.06.10, straight from http://cppreference.com β€” go read more, she's iconic, mwah πŸŽ€πŸ’–βœ¨

πŸ“¦ where this page comes from