Przejdź do głównej zawartości

std::string operator[]

// Non const version
constexpr reference operator[]( size_type pos );

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

Returns a reference

to the element at specified index pos.

uwaga

No bounds checking is performed.

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().

Parameters

  • pos - 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 <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
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 operator[]

// Non const version
constexpr reference operator[]( size_type pos );

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

Returns a reference

to the element at specified index pos.

uwaga

No bounds checking is performed.

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().

Parameters

  • pos - 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 <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
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.