Namespaces
Variants
Views
Actions

std::basic_string_view<CharT,Traits>::operator[]

From cppreference.com
 
 
 
 
constexpr const_reference operator[]( size_type pos ) const;
(since C++17)

Returns a const reference to the character at specified location pos.

If pos < size() is false, the behavior is undefined.

(until C++26)

If pos < 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.
(since C++26)

Contents

[edit] Parameters

pos - position of the character to return

[edit] Return value

data_ [pos]

[edit] Exceptions

Does not throw.

[edit] Complexity

Constant.

[edit] Notes

Unlike std::basic_string::operator[], std::basic_string_view::operator[](size()) does not return a reference to CharT().

[edit] Example

#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

[edit] See also

accesses the specified character with bounds checking
(public member function) [edit]
accesses the specified character
(public member function of std::basic_string<CharT,Traits,Allocator>) [edit]