Przejdź do głównej zawartości

std::string_view operator[]

// Const version only
constexpr const_reference operator[]( size_type pos ) const;

Returns a reference

to the element at specified index pos.

uwaga

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

.

Parameters

  • pos - position of the character to return

Return value

Reference to the requested character.

Exceptions

(none)

Complexity

Constant - O(1).

Notes

Unlike std::basic_string::operator[], std::basic_string_view::operator[](size()) has undefined behavior

instead of returning CharT().

Example

Main.cpp
#include <iostream>
#include <string_view>
int main()
{
std::string str = "Exemplar";
std::string_view v = str;
std::cout << v[2] << '\n';
// v[2] = 'y'; // Error: cannot modify through a string view
str[2] = 'y';
std::cout << v[2] << '\n';
}
Output
e
y
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::string_view operator[]

// Const version only
constexpr const_reference operator[]( size_type pos ) const;

Returns a reference

to the element at specified index pos.

uwaga

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

.

Parameters

  • pos - position of the character to return

Return value

Reference to the requested character.

Exceptions

(none)

Complexity

Constant - O(1).

Notes

Unlike std::basic_string::operator[], std::basic_string_view::operator[](size()) has undefined behavior

instead of returning CharT().

Example

Main.cpp
#include <iostream>
#include <string_view>
int main()
{
std::string str = "Exemplar";
std::string_view v = str;
std::cout << v[2] << '\n';
// v[2] = 'y'; // Error: cannot modify through a string view
str[2] = 'y';
std::cout << v[2] << '\n';
}
Output
e
y
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.