std::basic_string<CharT,Traits,Allocator>::operator[]_C++中文网

(1)

reference       operator[]( size_type pos );

(C++20 前)

constexpr reference       operator[]( size_type pos );

(C++20 起)
(2)

const_reference operator[]( size_type pos ) const;

(C++20 前)

constexpr const_reference operator[]( size_type pos ) const;

(C++20 起)

返回到位于指定位置 pos 的字符的引用。不进行边界检查。若 pos > size() ,则行为未定义。

1)pos == size() ,则行为未定义。

2)pos == size() ,则返回到拥有值 CharT() 的字符(空字符)的引用。

(C++11 前)

pos == size() ,则返回到拥有值 CharT() 的字符(空字符)的引用。

对于第一(非 const 版本),若修改此字符为任何异于 CharT() 的值,则行为未定义。

(C++11 起)

参数

返回值

到请求字符的引用。

复杂度

常数

示例

#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'; // 作为 C 字符串打印
 
    // 更改 s 的最后字符为 'y'
    std::string s("Exemplar ");
    s[s.size()-1] = 'y';
    std::cout << s << '\n';
}

输出:

参阅