std::span<T,Extent>::operator[]
来自cppreference.com
<tbody>
</tbody>
constexpr reference operator[]( size_type idx ) const; |
(C++20 起) | |
获得到序列的第 idx 个元素的引用。
|
如果 |
(C++26 前) |
|
如果 |
(C++26 起) |
参数
| idx | - | 要访问的元素的索引 |
返回值
data()[idx]
异常
不抛出。
示例
运行此代码
#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);
}
输出:
1 2 3 4 5
5 4 3 2 1
参阅
(C++26) |
带越界检查访问指定的元素 (公开成员函数) |
| 直接访问底层连续存储 (公开成员函数) | |
| 返回元素数 (公开成员函数) | |
(C++20) |
转换 span 为对其底层字节的视图 (函数模板) |