【问题标题】:a different way of initialising a 2d Array初始化二维数组的另一种方式
【发布时间】:2022-01-03 20:40:52
【问题描述】:
#include <array>

array<array<bool,50>,9>coordinates{};

我在代码中看到了这一点,但我不明白,这是声明二维数组的另一种方式吗?

【问题讨论】:

标签: c++ arrays


【解决方案1】:

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( ) 而不是&amp;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 数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-29
    • 2012-05-20
    • 1970-01-01
    • 2013-06-27
    • 2021-02-22
    相关资源
    最近更新 更多