std::basic_string<CharT,Traits,Allocator>::operator[]
来自cppreference.com
<tbody>
</tbody>
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 前) |
|
返回到 |
(C++11 起) |
2) 返回到
CharT() 的引用。|
如果 |
(C++26 前) |
|
如果 |
(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::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'; // 等价于 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> 的公开成员函数)
|