我们什么时候在 C++ 中使用数组而不是向量,反之亦然?

When do we use arrays over vectors in C++ and vice versa?

我从 this link 看到了以下内容:

Vectors are part of STL. Vectors in C++ are sequence containers representing arrays that can change their size during runtime . They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.

Vectors are the dynamic arrays that are used to store data.It is different from arrays which store sequential data and are static in nature, Vectors provide more flexibility to the program. Vectors can adjust their size automatically when an element is inserted or deleted from it.

如果vector能做这么多,在什么情况下我们还是偏爱数组?

谢谢!

If vectors can do so much, under what circumstances do we still prefer arrays?

一个好的设计不是没有什么可添加的,而是没有什么可以删除的。或者仅在需要时引入额外的复杂性。

std::vector 的一个主要缺点是它在必须增长时使用动态内存分配,这在执行时间方面可能非常昂贵。因此,在已知合理上限的情况下,使用固定长度的数组可能会更好,即使这会浪费内存 space。这个决定是space/timetrade-off.

但是,std::vector 的这个缺点可以通过调用 std::vector::reserve.

提前为一定数量的元素保留内存来缓解

使用 std::vector 的另一个缺点是 serialization 明显更难。例如,如果您使 std::array 成为 struct 的成员,那么您可以简单地逐字节复制整个 struct 内容以序列化它。但是,如果您使 std::vector 成为 struct 的成员,这是不可能的,因为它可能不会将实际数据存储在 struct 中,而可能只会存储指向的指针数据。因此,您将无法通过简单地复制 struct 的内存来序列化 struct。相反,序列化 std::vector 将需要特殊处理。