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

来自cppreference.com
< 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 < size() 时返回到位于指定位置 pos 的字符的引用,或在 pos == size() 时:

1)

行为未定义。

(C++11 前)

返回到 CharT() 的引用,如果返回的引用指代的对象被修改成 CharT() 以外的值,那么行为未定义。

(C++11 起)
2) 返回到 CharT() 的引用。

如果 pos > size()true,那么行为未定义。

(C++26 前)

如果 pos > size()true,那么:

  • 如果实现是硬化实现,那么就会发生契约违背。并且契约违背处理函数在“观察”求值语义下返回时行为未定义。
  • 如果实现不是硬化实现,那么行为未定义。
(C++26 起)

目录

[编辑]参数

pos - 要返回的字符位置

[编辑]返回值

1)pos < size() 时返回 *(begin()+ pos),或在 pos == size() 时返回到 CharT() 的引用(C++11 起)
2)pos < size() 时返回 *(begin()+ pos),或在 pos == size() 时返回到 CharT() 的引用。

[编辑]复杂度

常数。

[编辑]示例

#include <iostream>#include <string>   int main(){std::stringconst e("Exemplar");for(unsigned i = e.length()-1; i !=0; i /=2)std::cout<< e[i];std::cout<<'\n';   constchar* c =&e[0];std::cout<< c <<'\n';// 作为 C 字符串打印   // 将 s 的最后一个字符改成 'y'std::string s("Exemplar "); s[s.size()-1]='y';// 等价于 s.back() = 'y';std::cout<< s <<'\n';}

输出:

rmx Exemplar Exemplary

[编辑]缺陷报告

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

缺陷报告 应用于 出版时的行为 正确行为
LWG 259 C++98 重载 (1) 能返回 const 左值 data()[pos],而这是非良构的 更改为返回 *(begin()+ pos)
LWG 2475 C++11 如果 pos == size(),那么修改返回的引用指代的对象的行为未定义 修改成 CharT() 具有良好定义

[编辑]参阅

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