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


当前回答

STL is a heavily optimized library. In fact, it's even suggested to use STL in games where high performance might be needed. Arrays are too error prone to be used in day to day tasks. Today's compilers are also very smart and can really produce excellent code with STL. If you know what you are doing, STL can usually provide the necessary performance. For example by initializing vectors to required size (if you know from start), you can basically achieve the array performance. However, there might be cases where you still need arrays. When interfacing with low level code (i.e. assembly) or old libraries that require arrays, you might not be able to use vectors.

其他回答

STL is a heavily optimized library. In fact, it's even suggested to use STL in games where high performance might be needed. Arrays are too error prone to be used in day to day tasks. Today's compilers are also very smart and can really produce excellent code with STL. If you know what you are doing, STL can usually provide the necessary performance. For example by initializing vectors to required size (if you know from start), you can basically achieve the array performance. However, there might be cases where you still need arrays. When interfacing with low level code (i.e. assembly) or old libraries that require arrays, you might not be able to use vectors.

如果不需要动态调整大小,则会有存储容量的内存开销(一个指针/size_t)。就是这样。

假设一个固定长度的数组(例如int* v = new int[1000];vs std::vector<int> v(1000);, v的大小保持固定在1000),唯一真正重要的性能考虑因素(或者至少对我来说,当我处于类似的困境时)是访问元素的速度。我查了一下STL的向量代码,下面是我的发现:

const_reference
operator[](size_type __n) const
{ return *(this->_M_impl._M_start + __n); }

这个函数肯定会被编译器内联。所以,只要你计划对v做的唯一一件事就是用operator[]访问它的元素,看起来在性能上不应该有任何差别。

两者之间的性能差异很大程度上取决于实现——如果你比较一个实现得很差的std::vector和一个优化的数组实现,数组会赢,但是反过来,vector会赢……

As long as you compare apples with apples (either both the array and the vector have a fixed number of elements, or both get resized dynamically) I would think that the performance difference is negligible as long as you follow got STL coding practise. Don't forget that using standard C++ containers also allows you to make use of the pre-rolled algorithms that are part of the standard C++ library and most of them are likely to be better performing than the average implementation of the same algorithm you build yourself.

也就是说,以我之见,vector在使用调试STL的调试场景中胜出,因为大多数具有适当调试模式的STL实现至少可以突出/清除人们在使用标准容器时所犯的典型错误。

哦,不要忘记数组和vector共享相同的内存布局,因此您可以使用vector将数据传递给需要基本数组的遗留C或c++代码。但是,请记住,在这种情况下,大多数赌注都是无效的,您将再次处理原始内存。

为了回应Mehrdad说过的话:

然而,在某些情况下 你仍然需要数组。当 与低级代码(例如: 程序集)或旧的库 需要数组,您可能无法 用向量。

完全不是这样的。向量可以很好地降级为数组/指针,如果你使用:

vector<double> vector;
vector.push_back(42);

double *array = &(*vector.begin());

// pass the array to whatever low-level code you have

这适用于所有主要的STL实现。在下一个标准中,它将被要求工作(即使它现在做得很好)。