std::span<T,Extent>::operator[]
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Containers library
(C++17)
(C++11)
(C++26)
(C++26)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++23)
(C++23)
(C++23)
(C++23)
(C++20)
(C++23)
Tables
std::span
(C++26)
span::operator[]
(C++23)
(C++23)
(C++23)
(C++23)
constexpr reference operator[]( size_type idx ) const;
(since C++20)
Returns a reference to the idxth element of the sequence.
If idx < size() is false, the behavior is undefined.
(until C++26)If idx < size() is false:
- If the implementation is hardened, a contract violation occurs. Moreover, if the contract-violation handler returns under "observe" evaluation semantic, the behavior is undefined.
- If the implementation is not hardened, the behavior is undefined.
[edit] Parameters
idx
-
the index of the element to access
[edit] Return value
data()[idx]
[edit] Exceptions
Throws nothing.
[edit] Example
Run this code
#include <cstddef> #include <iostream> #include <span> #include <utility> void reverse(std::span <int> span) { for (std::size_t i = 0, j = std::size (span); i < j; ++i) { --j; std::swap (span[i], span[j]); } } void print(const std::span <const int> span) { for (int element : span) std::cout << element << ' '; std::cout << '\n'; } int main() { int data[]{1, 2, 3, 4, 5}; print(data); reverse(data); print(data); }
Output:
1 2 3 4 5 5 4 3 2 1