std::array at() 方法
- 自 C++17 起
- 自 C++14 起
- 直到 C++14
// 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
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
处的元素。会执行边界检查,如果访问无效,将抛出 std::out_of_range
类型的异常。
参数
pos
- 要返回的元素的位置
返回值
对请求元素的引用。
异常
如果 pos >= size()
,则抛出 std::out_of_range
。
复杂度
常数。
示例
Main.cpp
#include <stdexcept>
#include <iostream>
#include <array>
int main()
{
std::array s("message"); // for capacity
s = "abc";
s.at(2) = 'x'; // ok
std::cout << s << '\n';
std::cout << "array size = " << s.size() << '\n';
std::cout << "array 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
array size = 3
array capacity = 7
basic_array::at