Skip to main content

std::array at() method

// Non const version
constexpr reference at( size_type pos );

// Const version
constexpr const_reference at( size_type pos ) const;

Returns a reference

to the element at specified index pos. Bounds checking is performed, exception of type std::out_of_range will be thrown on invalid access.

Parameters

  • pos - position of the element to return

Return value

Reference to the requested element.

Exceptions

Throws std::out_of_range if pos >= size().

Complexity

Constant.

Example

Main.cpp
#include <stdexcept>
#include <iostream>
#include <array>

int main()
{
std::array s("message"); // for capacity

s = "abc";
s.at(2) = 'x'; // ok
std::cout << s << '\n';

std::cout << "array size = " << s.size() << '\n';
std::cout << "array capacity = " << s.capacity() << '\n';

try {
// This will throw since the requested offset
// is greater than the current size.
s.at(3) = 'x';
}
catch (std::out_of_range const& exc) {
std::cout << exc.what() << '\n';
}
}
Possible output
abx
array size = 3
array capacity = 7
basic_array::at
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::array at() method

// Non const version
constexpr reference at( size_type pos );

// Const version
constexpr const_reference at( size_type pos ) const;

Returns a reference

to the element at specified index pos. Bounds checking is performed, exception of type std::out_of_range will be thrown on invalid access.

Parameters

  • pos - position of the element to return

Return value

Reference to the requested element.

Exceptions

Throws std::out_of_range if pos >= size().

Complexity

Constant.

Example

Main.cpp
#include <stdexcept>
#include <iostream>
#include <array>

int main()
{
std::array s("message"); // for capacity

s = "abc";
s.at(2) = 'x'; // ok
std::cout << s << '\n';

std::cout << "array size = " << s.size() << '\n';
std::cout << "array capacity = " << s.capacity() << '\n';

try {
// This will throw since the requested offset
// is greater than the current size.
s.at(3) = 'x';
}
catch (std::out_of_range const& exc) {
std::cout << exc.what() << '\n';
}
}
Possible output
abx
array size = 3
array capacity = 7
basic_array::at
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.