std::array 是一个结构体模板:
template<class T, std::size_t N> struct array;
根据 cppreference.com,与 C 样式数组相比,它有几个优点,如下所示:
该结构将 C 样式数组的性能和可访问性与标准容器的优点结合在一起,例如知道自己的大小、支持赋值、随机访问迭代器等。
使用 C 风格的数组,您必须像 bool coordinates[ 9 ][ 50 ] { }; 一样编写它。这里 9 是行数,50 是列数。
现在让我们简要看一下一些代码。如果你运行这段代码:
#include <array>
int main( )
{
std::array< std::array<bool,50>, 9 > coordinates{ };
std::cout << sizeof( coordinates ) << '\n';
}
你会看到:
450
这意味着coordinates 在堆栈上占用 9 * 50 == 450 字节的内存。这种类型的数组不是动态分配的(不像std::vector)。
这个:
// Prefer the upper one
std::cout << "Pointer to the underlying array: " << coordinates.data( ) << '\n';
std::cout << "Pointer to the underlying array: " << &coordinates << '\n';
会产生类似这样的结果:
Pointer to the underlying array: 0x8a651ff540
Pointer to the underlying array: 0x8a651ff540
但你应该更喜欢coordinates.data( ) 而不是&coordinates[0]。
还有这个:
std::cout << "Number of elements: " << coordinates.size( ) << '\n';
std::cout << "Maximum possible number of elements: " << coordinates.max_size( ) << '\n';
会给这个:
Number of elements: 9
Maximum possible number of elements: 9
可以看出,与传统的C 数组 不同,std::array 有许多可以帮助程序员的成员函数。不仅如此,使用起来也更安全。最后但同样重要的是,std::array 在性能方面相当于 C 数组。