std::basic_string<CharT,Traits,Allocator>::operator[]

From cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
Member functions
Element access
basic_string::operator[]
Iterators
Capacity
Operations
Search
Constants
Deduction guides (C++17)
Non-member functions
I/O
Comparison
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
Numeric conversion
(C++11)(C++11)(C++11)
(C++11)(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
Helper classes
 
(1)
reference operator[]( size_type pos );
(until C++20)
constexpr reference operator[]( size_type pos );
(since C++20)
(2)
const_reference operator[]( size_type pos ) const;
(until C++20)
constexpr const_reference operator[]( size_type pos ) const;
(since C++20)

Returns a reference to the character at specified location pos. No bounds checking is performed. If pos > size(), the behavior is undefined.

1) If pos == size(), the behavior is undefined.
2) If pos == size(), a reference to the character with value CharT() (the null character) is returned.
(until C++11)

If pos == size(), a reference to the character with value CharT() (the null character) is returned.

For the first (non-const) version, the behavior is undefined if this character is modified to any value other than CharT() .

(since C++11)

Parameters

pos - position of the character to return

Return value

Reference to the requested character.

Complexity

Constant.

Example

#include <iostream>
#include <string>
 
int main()
{
    std::string const e("Exemplar");
    for (unsigned i = e.length() - 1; i != 0; i /= 2)
        std::cout << e[i];
    std::cout << '\n';
 
    const char* c = &e[0];
    std::cout << c << '\n'; // print as a C string
 
    //Change the last character of s into a 'y'
    std::string s("Exemplar ");
    s[s.size()-1] = 'y'; // equivalent to s.back() = 'y';
    std::cout << s << '\n';
}

Output:

rmx
Exemplar
Exemplary

See also

accesses the specified character with bounds checking
(public member function)
(C++11)
accesses the first character
(public member function)
(C++11)
accesses the last character
(public member function)
accesses the specified character
(public member function of std::basic_string_view<CharT,Traits>)