跳到主要内容

std::string at() 方法

// Non const version
constexpr reference at( size_type pos );

// Const version
constexpr const_reference at( size_type pos ) const;

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

返回指定索引 pos 处的字符。

执行边界检查。

参数

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

返回值

对所请求字符的引用。

异常

如果pos >= size(),则抛出std::out_of_range

复杂度

常数 - O(1)

示例

#include <stdexcept>
#include <iostream>
#include <string>

int main()
{
std::string s("message"); // for capacity

s = "abc";
s.at(2) = 'x'; // ok
std::cout << s << '\n';

std::cout << "string size = " << s.size() << '\n';
std::cout << "string capacity = " << s.capacity() << '\n';

try {
// This will throw since the requested offset is greater than the current size.
s.at(3) = 'x';
}
catch (std::out_of_range const& exc) {
std::cout << exc.what() << '\n';
}
}
可能输出
abx
string size = 3
string capacity = 7
basic_string::at
本文档源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档所做的所有更改。
悬停查看原始许可证。

std::string at() 方法

// Non const version
constexpr reference at( size_type pos );

// Const version
constexpr const_reference at( size_type pos ) const;

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

返回指定索引 pos 处的字符。

执行边界检查。

参数

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

返回值

对所请求字符的引用。

异常

如果pos >= size(),则抛出std::out_of_range

复杂度

常数 - O(1)

示例

#include <stdexcept>
#include <iostream>
#include <string>

int main()
{
std::string s("message"); // for capacity

s = "abc";
s.at(2) = 'x'; // ok
std::cout << s << '\n';

std::cout << "string size = " << s.size() << '\n';
std::cout << "string capacity = " << s.capacity() << '\n';

try {
// This will throw since the requested offset is greater than the current size.
s.at(3) = 'x';
}
catch (std::out_of_range const& exc) {
std::cout << exc.what() << '\n';
}
}
可能输出
abx
string size = 3
string capacity = 7
basic_string::at
本文档源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档所做的所有更改。
悬停查看原始许可证。