在我们的c++课程中,他们建议不要再在新项目中使用c++数组。据我所知,Stroustroup本人建议不要使用数组。但是否存在显著的性能差异?


当前回答

There is no argument about which of them is the best or good to use.They both have there own use cases,they both have their pros and cons.The behavior of both containers are different in different places.One of the main difficulty with arrays is that they are fixed in size if once they are defined or initialized then you can not change values and on the other side vectors are flexible, you can change vectors value whenever you want it's not fixed in size like arrays,because array has static memory allocation and vector has dynamic memory or heap memory allocation(we can push and pop elements into/from vector) and the creator of c++ Bjarne Stroustrup said that vectors are flexible to use more than arrays.

应该避免使用带有new的c++数组(即使用动态数组)。有一个问题是,你必须跟踪它们的大小,你需要手动删除它们,并做所有的家务工作。

我们还可以很容易地在向量中插入、推入和拉出值,这在数组中是不容易做到的。

如果我们讨论性能,那么如果你处理小的值,那么你应该使用数组,如果你处理大规模的代码,那么你应该使用向量(向量比数组更擅长处理大的值)。

其他回答

如果在调试模式下编译软件,许多编译器将不会内联vector的访问器函数。这将使stl向量的实现在性能有问题的情况下变得更慢。它还将使代码更容易调试,因为您可以在调试器中看到分配了多少内存。

在优化模式下,我希望stl向量接近数组的效率。这是因为许多vector方法现在都内联了。

关于杜里的贡献和我自己的测量。

结论是整数数组比整数向量快(在我的例子中是5倍)。然而,对于更复杂/未对齐的数据,数组和向量的速度大致相同。

There is no argument about which of them is the best or good to use.They both have there own use cases,they both have their pros and cons.The behavior of both containers are different in different places.One of the main difficulty with arrays is that they are fixed in size if once they are defined or initialized then you can not change values and on the other side vectors are flexible, you can change vectors value whenever you want it's not fixed in size like arrays,because array has static memory allocation and vector has dynamic memory or heap memory allocation(we can push and pop elements into/from vector) and the creator of c++ Bjarne Stroustrup said that vectors are flexible to use more than arrays.

应该避免使用带有new的c++数组(即使用动态数组)。有一个问题是,你必须跟踪它们的大小,你需要手动删除它们,并做所有的家务工作。

我们还可以很容易地在向量中插入、推入和拉出值,这在数组中是不容易做到的。

如果我们讨论性能,那么如果你处理小的值,那么你应该使用数组,如果你处理大规模的代码,那么你应该使用向量(向量比数组更擅长处理大的值)。

可能会有一些边缘情况,你在内联函数中有一个向量访问在内联函数中,你已经超出了编译器将内联的范围,它将强制函数调用。这种情况太罕见了,不值得担心——总的来说,我同意litb的观点。

我很惊讶居然没有人提到这一点——不要担心性能,直到它被证明是一个问题,然后进行基准测试。

选择STL。没有性能损失。这些算法非常高效,它们在处理我们大多数人不会想到的细节方面做得很好。