std::span::at(3)
πΈ 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_rangeifpos >= 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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms