定义于: <array>
概述
template <typename T, std::size_t N>
class array
std::array
是一个封装固定大小数组的容器。它是 C 风格数组 T arr[N]
更安全的替代品。
使用示例
本节中的示例非常简单。有关更多示例,请导航到底部的示例部分。
- 创建
- 填充并打印
- 排序
- C++20
- C++17
- C++17 之前
- 字符串字面量
要创建具有自动推导大小和/或类型的数组,我们可以使用std::to_array
(自 C++20 起)。
注意:类型和大小推导(同时)自 C++17 起即可。
#include <array>
int main() {
// type: std::array<int, 4>
auto ints = std::to_array({1, 5, 3, 7});
// type: std::array<float, 4>
auto floats = std::to_array<float>({1, 5, 3, 7});
// type: std::array<char, 6>
auto hello = std::to_array("Hello");
// this is different to std::array{"Hello"}, which creates std::array<char const*, 1>
}
使用 CTAD
#include <array>
int main() {
std::array numbers{1, 2, 4, 8};
// Content: 1,2,4,8
// ❌ Error, cannot deduce size only (look C++20 to_array)
std::array<int> numbers{1, 2, 4, 8};
}
不幸的是,无法推导。
#include <array>
int main() {
std::array<int, 8> numbers = {1, 2, 4, 8};
// Content: 1,2,4,8,0,0,0,0
}
注意:仅当您没有 C++20 时才推荐使用此方法,否则请使用std::to_array
。
#include <array>
int main() {
std::array<char, 6> str = { "Hello" };
// Content: 'H','e','l','l','o', <nul>
}
#include <iostream>
#include <array>
int main()
{
std::array<int, 4> playerScores{}; // initialize with zeros
for (int score : playerScores)
std::cout << score << ", ";
playerScores.fill(123);
playerScores.back() = 30;
std::cout << '\n';
for (int score : playerScores)
std::cout << score << ", ";
}
- C++20
- 直到 C++20
注意:ranges
自 C++20 起可用。
#include <array>
#include <algorithm>
int main() {
std::array<int, 4> numbers = {13, 2, 7, 4};
// Content: 13,2,7,4
std::ranges::sort(numbers);
// Content: 2,4,7,13
}
#include <array>
#include <algorithm>
int main() {
std::array<int, 4> numbers = {13, 2, 7, 4};
// Content: 13,2,7,4
std::sort(numbers.begin(), numbers.end());
// Content: 2,4,7,13
}
内存
数组的元素在内存中是连续存储的。

技术细节
数组的技术定义
此容器是一种聚合类型,其语义与包含 C 风格数组 T[N]
作为其唯一非静态数据成员的结构体相同。与 C 风格数组不同,它不会自动退化为 T*
。作为聚合类型,它可以使用聚合初始化进行初始化,给定最多 N
个可转换为 T
的初始化器
std::array<int, 3> a = {1,2,3};
该结构体结合了 C 风格数组的性能和可访问性,以及标准容器的优点,例如了解其自身大小、支持赋值、随机访问迭代器等。
数组也可以用作相同类型的 N
个元素的元组。
零长度数组 (N == 0
)
对于零长度数组 (N == 0
) 有一个特殊情况。在这种情况下,array.begin() == array.end()
,这是一个唯一的值。在零大小数组上调用 front()
或 back()
的效果是未定义的。
命名要求
std::array
满足以下要求
除了默认构造的数组不为空且交换的复杂度是线性的
满足以下要求
ContiguousContainer
(自 C++17 起)SequenceContainer
(部分)
std::array
定义于 | 数组 |
模板参数
pub | T | 元素的类型 |
pub | N | 元素数量(编译时常量) |
类型名称
pub | value_type | T |
pub | size_type | std::size_t |
pub | difference_type | std::ptrdiff_t |
pub | reference | value_type& |
pub | const_reference | value_type const& |
pub | pointer | value_type* |
pub | const_pointer | value_type const* |
pub | iterator | LegacyRandomAccessIterator 到 value_type |
pub | const_iterator | LegacyRandomAccessIterator 到 value_type const |
pub | reverse_iterator | std::reverse_iterator<iterator> |
pub | const_reverse_iterator | std::reverse_iterator<const_iterator> |
成员函数
pub | (构造函数) | 根据聚合初始化规则构造一个数组。 |
pub | (析构函数) | 销毁数组的每个元素。 |
pub | operator= | 用另一个数组的相应元素覆盖数组的每个元素。 |
元素访问
pub | at | 进行边界检查以访问指定元素。 |
pub | operator[] | 访问元素。 |
pub | front | 返回第一个元素。 |
pub | 末尾 | 返回最后一个元素。 |
pub | 数据 | 返回指向底层数组第一个元素的指针。 |
迭代器
pub | begin cbegin | 返回指向起始元素的iterator/const_iterator 。 |
pub | end cend | 返回指向结束元素的iterator/const_iterator 。 |
pub | rbegin crbegin | 返回一个反向 iterator/const_iterator 指向起始位置。 |
pub | rend crend | 返回一个反向 iterator/const_iterator 指向结束位置。 |
容量
pub | empty | 如果容器为空,则返回 true ,否则返回 false 。 |
pub | size | 返回元素数量。 |
pub | max_size | 返回最大可能的元素数量。 |
操作
pub | fill | 用指定值填充容器。 |
pub | swap | 交换内容。 |
非成员函数
pub | operator== operator!= operator< operator> operator<= operator>= operator<=> | 按字典顺序比较数组中的值。 |
pub | std::get (std::array) | 访问数组的元素。 |
pub | std::swap (std::array) | 特化 std::swap 算法。 |
pub | std::to_array (C++20) | 从内置数组创建 std::array 对象。 |
辅助类
pub | std::tuple_size<std::array> (C++11) | 获取数组的大小。 |
pub | std::tuple_element<std::array> (C++11) | 获取数组元素的类型。 |
推导指南 (C++17 起)
点击展开
推导指南
// (1)
template< class T, class... U >
array( T, U... ) -> array<T, 1 + sizeof...(U)>;
(1) 允许从可变参数包推导
其目的是提供std::experimental::make_array
的等价物。
如果任何 U
与 T
不同 (std::is_same_v<T, U> && ...
),则程序格式不正确。
允许空参数包,此时 std::array
的类型为 std::array<T, 1>
。
更多示例
使用算法
#include <iostream>
#include <array>
#include <algorithm>
int main()
{
namespace rg = std::ranges;
auto numbers = std::to_array({ 12, 3, 18, 9});
// Find minimal element
auto minIt = rg::min_element(numbers);
// obtain value:
auto value = *minIt;
// find position:
auto index = std::distance(numbers.begin(), minIt);
std::cout << "Min: " << value
<< ", at index: " << index
<< std::endl;
}
Min: 3, at index: 1
高级
#include <fstream>
#include <array>
#include <string>
std::string readFile(std::istream& file)
{
constexpr size_t BUFFER_SIZE = 16 * 1024; // 16 KB
constexpr size_t RESERVE_SIZE = 1 * 1024 * 1024; // 1 MB
std::string result;
result.reserve(RESERVE_SIZE); // 1 MB
std::array<char, BUFFER_SIZE> buf;
while(file.read(buf.data(), buf.size()))
result.append(buf.data(), buf.data() + file.gcount());
result.append(buf.data(), buf.data() + file.gcount());
return result;
}
// Example usage:
int main()
{
std::ifstream file("hello.txt");
if (file.is_open())
{
auto fileContents = readFile(file);
// ...
}
}
#include <iostream>
#include <array>
#include <algorithm>
template <typename T, size_t N1, size_t N2>
auto concat(
std::array<T, N1> const& lhs,
std::array<T, N2> const& rhs
)
{
namespace rg = std::ranges;
std::array<T, N1 + N2> result;
rg::copy(lhs, result.begin());
rg::copy_backward(rhs, result.end());
return result;
}
int main()
{
auto left = std::to_array({1, 2, 3});
auto right = std::to_array({4, 5, 6});
auto both = concat(left, right);
for (int elem : both)
std::cout << elem << ' ';
}
1 2 3 4 5 6