std::string at() 方法
- 自 C++20 起
- 直到 C++20
// Non const version
constexpr reference at( size_type pos );
// Const version
constexpr const_reference at( size_type pos ) const;
// Non const version
reference at( size_type pos );
// Const version
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