命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
CharT& operator[]( size_type pos );
(1) (C++20 起为 constexpr)
const CharT& operator[]( size_type pos ) const;
(2) (C++20 起为 constexpr)

返回指定位置 pos 的字符的引用,如果 pos < size(),或者返回 CharT() 的引用,如果 pos == size()。不执行边界检查。

如果 pos > size(),则行为未定义。

对于重载 (1),如果 pos == size(),则行为未定义,除非被返回引用指向的对象被修改为除 CharT() 以外的任何值(C++11 起)

目录

[编辑] 参数

pos - 要返回的字符的位置

[编辑] 返回值

如果 pos < size(),则返回所请求元素的引用;如果 pos == size(),则返回 CharT() 的引用。

[编辑] 复杂度

常数时间。

[编辑] 示例

#include <iostream>
#include <string>
 
int main()
{
    const std::string 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';
}

输出

rmx
Exemplar
Exemplary

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 259 C++98 非 const 重载可以返回 const 左值 data()[pos],这是非良构的 改为返回
*(begin() + pos)
LWG 2475 C++11 如果 pos == size(),修改
返回引用指向的对象的行为未定义
如果修改为 CharT(),则行为良好定义
修改为 CharT()

[编辑] 参阅

带边界检查访问指定字符
(公有成员函数) [编辑]
(DR*)
访问第一个字符
(公有成员函数) [编辑]
(DR*)
访问最后一个字符
(公有成员函数) [编辑]
访问指定的字符
(std::basic_string_view<CharT,Traits> 的公有成员函数) [编辑]