std::mdspan<T,Extents,LayoutPolicy,AccessorPolicy>::at
From cppreference.com
template< class... OtherIndexTypes >
constexpr reference at( OtherIndexTypes... indices ) const;
|
(1) | (since C++26) |
template< class OtherIndexType >
constexpr reference
at( std::span<OtherIndexType, rank()> indices ) const;
|
(2) | (since C++26) |
template< class OtherIndexType >
constexpr reference
at( const std::array<OtherIndexType, rank()>& indices ) const;
|
(3) | (since C++26) |
Returns a reference to the indicesth element of the mdspan, with bounds checking.
1) Equivalent to
return acc_ .access(ptr_, map_ (static_cast<index_type>(std::move(indices))...));. This overload participates in overload resolution only if all following values are
true:
(std::is_convertible_v<OtherIndexTypes, index_type> && ...)(std::is_nothrow_constructible_v<index_type, OtherIndexTypes> && ...)sizeof...(OtherIndexTypes) == rank()
If
extents_type::index-cast (std::move(indices)) is not a multidimensional index in extents(), an exception of type std::out_of_range is thrown.2,3) Let
P be a parameter pack such that
std::is_same_v<std::make_index_sequence<rank()>
std::index_sequence<P...>>
true, equivalent to return at(extents_type::index-cast (std::as_const(indices[P]))...);. This overload participates in overload resolution only if all following values are
true:
std::is_convertible_v<const OtherIndexType&, index_type>std::is_nothrow_constructible_v<index_type, const OtherIndexType&>
Parameters
| indices | - | the indices of the element to access |
Return value
A reference to the element.
Exceptions
Throws an exception of type std::out_of_range if indices is an invalid index.
Example
Run this code
#include <array>
#include <cassert>
#include <mdspan>
#include <print>
#include <span>
int main()
{
std::array data // row-major 2 x 3 matrix
{
10, 11, 12, // row 0
20, 21, 22 // row 1
};
std::mdspan m{data.data(), 2, 3}; // 2D mdspan (2 rows, 3 columns)
std::array<std::size_t, 2> arr_indices{1, 0};
std::span<const std::size_t, 2> span_indices{arr_indices};
assert(m.at(1, 2) == 22); // OK; overload (1)
assert(m.at(span_indices) == 20); // OK; overload (2)
assert(m.at(arr_indices) == 20); // OK; overload (3)
try
{
auto x_x = m.at(1, 3); // throws
}
catch (const std::out_of_range& ex)
{
std::print("{}\n", ex.what());
}
}
Possible output:
mdspan::at: 1th index (which is 3) >= extent(1) (which is 3)
See also
| accesses an element at the specified multidimensional index (public member function) |