Skip to main content

std::span operator[]

constexpr reference operator[](size_type idx) const;

Returns a reference

to the element at specified index idx.

caution

No bounds checking is performed, using an element out of bounds is undefined behavior

.

Parameters

  • idx - position of the character to return

Return value

Reference to the requested character.

Exceptions

(none)

Complexity

Constant - O(1).

Example

Main.cpp
#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(std::span<const int> const 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
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::span operator[]

constexpr reference operator[](size_type idx) const;

Returns a reference

to the element at specified index idx.

caution

No bounds checking is performed, using an element out of bounds is undefined behavior

.

Parameters

  • idx - position of the character to return

Return value

Reference to the requested character.

Exceptions

(none)

Complexity

Constant - O(1).

Example

Main.cpp
#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(std::span<const int> const 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
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.