std::array::at(3)
π std::array::at(3) π
Hey bestie! π Welcome to the std::array::at(3) page, straight from the C++ Standard Libary β yes, βLibary,β thatβs literally how itβs written in the header, and Iβm obsessed with the commitment. π«Ά Today weβre grabbing an element from a std::array with bounds checking, and honestly? Sheβs a responsible queen. π
π NAME π
std::array::at - std::array::at
β¨ Synopsis β¨
Two overloads, bestie β both since C++11, with constexpr upgrades later: overload (1) gets constexpr since C++17, overload (2) since C++14. π
reference at( size_type pos ); (1) (since C++11)
(constexpr since
C++17)
const_reference at( size_type pos ) const; (2) (since C++11)
(constexpr since
C++14)
Okay so what it does: it returns a reference to the element at the specified location pos, and it does it with bounds checking. π
And if pos is not within the range of the container, an exception of type std::out_of_range is thrown. No cap, thatβs the rule. π
π§Έ Parameters π§Έ
posβ position of the element to return.
π Return value π
A reference to the requested element. Thatβs it. Thatβs the tea. π
π¨ Exceptions π¨
std::out_of_range if pos >= size().
So if pos >= size(), boom β std::out_of_range. Periodt. π¨
β‘ Complexity β‘
Constant. Thatβs the whole section, and she ate. β‘
π» Example π»
Run this code, bestie β itβs all here, every line:
// Run this code
#include <iostream>
#include <array>
#include <stdexcept>
#ifdef __GNUG__
[[gnu::noinline]]
#endif
unsigned int runtime_six() // Emulate runtime input
{
return 6u;
}
int main()
{
std::array<int, 6> data = {1, 2, 4, 5, 5, 6};
// 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
array::at: __n (which is 6) >= _Nm (which is 6)
data: 1 88 4 5 5 6
π See also π
operator[]β access specified element (public member function).
Thatβs the page, bestie! π It came from http://cppreference.com, dated 2024.06.10, and itβs the std::array::at(3) manual page. 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