跳到主要内容

std::string operator[]

// Non const version
constexpr reference operator[]( size_type pos );

// Const version
constexpr const_reference operator[]( size_type pos ) const;

返回对指定索引pos处元素的引用

执行边界检查。

注意

不执行边界检查。

如果 pos == size(),则返回对值为 CharT() 的字符(**空字符**)的引用。

对于第一个(非 const)版本,如果此字符被修改为 CharT() 以外的任何值,则行为未定义

如果此字符被修改为 CharT() 以外的任何值,则行为未定义。

参数

  • pos - 要返回的字符的位置

返回值

对所请求字符的引用。

异常

(无)

复杂度

常数 - O(1)

示例

Main.cpp
#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'; // 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
本文档源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了更改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string operator[]

// Non const version
constexpr reference operator[]( size_type pos );

// Const version
constexpr const_reference operator[]( size_type pos ) const;

返回对指定索引pos处元素的引用

执行边界检查。

注意

不执行边界检查。

如果 pos == size(),则返回对值为 CharT() 的字符(**空字符**)的引用。

对于第一个(非 const)版本,如果此字符被修改为 CharT() 以外的任何值,则行为未定义

如果此字符被修改为 CharT() 以外的任何值,则行为未定义。

参数

  • pos - 要返回的字符的位置

返回值

对所请求字符的引用。

异常

(无)

复杂度

常数 - O(1)

示例

Main.cpp
#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'; // 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
本文档源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了更改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。