std::string_view operator[]
- od C++17
// Const version only
constexpr const_reference operator[]( size_type pos ) const;
Returns a reference
to the element at specified indexpos
.
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
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.
Hover to see the original license.