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

C++ 参考手册

位置:首页 > C++ 参考手册 >字符串库 >std::basic_string > std::basic_string<CharT,Traits,Allocator>::operator[]

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

1) 若 pos == size() ,则行为未定义。
2) 若 pos == size() ,则返回到拥有值 CharT() 的字符(空字符)的引用。
(C++11 前)

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

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

(C++11 èµ·)

参数

pos - 要返回的字符位置

返回值

到请求字符的引用。

复杂度

常数

示例

#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';
}

输出:

rmx
Exemplar
Exemplary

参阅