跳到主要内容

std::array at() 方法

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

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

std::array at() 方法

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

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