std::ranges::view_interface<D>::at
From cppreference.com
template< ranges::random_access_range R = D >
requires ranges::sized_range<R >
constexpr decltype(auto)
at( ranges::range_difference_t<R> n ); // freestanding-deleted
|
(1) | (since C++26) |
template< ranges::random_access_range R = const D >
requires ranges::ranges::sized_range<R>
constexpr decltype(auto)
at( ranges::range_difference_t<R> n ) const; // freestanding-deleted
|
(2) | (since C++26) |
The default implementation of at member function obtains the element at the specified offset relative to the beginning iterator, reusing the at of the iterator type.
1) Let
derived be static_cast<D&>(*this). Equivalent to return (*this)[n];.2) Same as (1), except that
derived is static_cast<const D&>(*this).Parameters
| n | - | position of the element to return |
Return value
The element at offset n relative to the beginning iterator.
Exceptions
Throws std::out_of_range if n < 0 is true or n >= ranges::distance(derived()) is true.
Notes
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_view_interface |
202606L |
(C++29) | ranges::view_interface::at
|
Example
Run this code
#include <iostream>
#include <ranges>
#include <stdexcept>
#include <vector>
int main()
{
std::vector nums{10, 20, 30, 40, 50};
// Create drop_view (which inherits from view_interface)
auto my_view{ nums | std::views::drop(1) }; // Elements: [20, 30, 40, 50]
try
{
// Non-throwing case, index inside the view bounds [0, 4)
std::cout << "Element at index 2: " << my_view.at(2) << '\n';
// Throwing case, my_view only has 4 elements, indices [0, 1, 2, 3]
std::cout << "Element at index 4: " << my_view.at(4) << '\n';
}
catch (const std::out_of_range& e)
{
std::cout << e.what() << '\n';
}
}
Possible output:
Element at index 2: 40
Exception: view_interface::_M_range_check: __n (which is 4) >= this->size() (which is 4)
See also
(C++26) |
access specified element with bounds checking (public member function of std::span<T,Extent>)
|
| access specified element with bounds checking (public member function of std::vector<T,Allocator>)
| |
| access specified element with bounds checking (public member function of std::array<T,N>)
| |
| access specified element with bounds checking (public member function of std::deque<T,Allocator>)
| |
| accesses the specified character with bounds checking (public member function of std::basic_string<CharT,Traits,Allocator>)
| |
| accesses the specified character with bounds checking (public member function of std::basic_string_view<CharT,Traits>)
|