在我们的c++课程中,他们建议不要再在新项目中使用c++数组。据我所知,Stroustroup本人建议不要使用数组。但是否存在显著的性能差异?
当前回答
有时候数组确实比向量好。如果你总是在操纵别人 固定长度的对象集合,数组更好。考虑下面的代码片段:
int main() {
int v[3];
v[0]=1; v[1]=2;v[2]=3;
int sum;
int starttime=time(NULL);
cout << starttime << endl;
for (int i=0;i<50000;i++)
for (int j=0;j<10000;j++) {
X x(v);
sum+=x.first();
}
int endtime=time(NULL);
cout << endtime << endl;
cout << endtime - starttime << endl;
}
X的向量在哪里
class X {
vector<int> vec;
public:
X(const vector<int>& v) {vec = v;}
int first() { return vec[0];}
};
X的数组版本为:
class X {
int f[3];
public:
X(int a[]) {f[0]=a[0]; f[1]=a[1];f[2]=a[2];}
int first() { return f[0];}
};
数组版本的main()将更快,因为我们避免了 每次在内部循环中“new”的开销。
(此代码由我发布到comp.lang.c++)。
其他回答
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。没有性能损失。这些算法非常高效,它们在处理我们大多数人不会想到的细节方面做得很好。
为了回应Mehrdad说过的话:
然而,在某些情况下 你仍然需要数组。当 与低级代码(例如: 程序集)或旧的库 需要数组,您可能无法 用向量。
完全不是这样的。向量可以很好地降级为数组/指针,如果你使用:
vector<double> vector;
vector.push_back(42);
double *array = &(*vector.begin());
// pass the array to whatever low-level code you have
这适用于所有主要的STL实现。在下一个标准中,它将被要求工作(即使它现在做得很好)。
下面是简单的测试:
c++数组vs Vector性能测试说明
与“对向量和数组/指针的基本索引、解引用和增量操作生成的汇编代码的比较”的结论相矛盾。
数组和向量之间一定有区别。测试是这么说的…试试吧,代码就在那里……
在c++ 11中使用普通数组的理由就更少了。
从最快到最慢,本质上有3种类型的数组,这取决于它们所具有的特性(当然,实现的质量可以使事情变得非常快,即使是列表中的情况3):
静态的,在编译时大小已知。——std::array<T, N> 动态的,运行时大小已知,从不调整大小。这里的典型优化是,如果数组可以直接分配到堆栈中。——不可用。也许在c++ 14之后,在c++ TS中使用dynarray。在C中有vla 动态的,可在运行时调整大小。——std::向量T > <
为1。常量静态数组,在c++ 11中使用std::array<T, N>。
为2。在运行时指定固定大小的数组,但这不会改变它们的大小,在c++ 14中有讨论,但它已经转移到技术规范,最终由c++ 14制成。
为3。std::vector<T>通常会在堆中请求内存。这可能会影响性能,不过可以使用std::vector<T, MyAlloc<T>>来使用自定义分配器改善这种情况。相对于T mytype[] = new mytype[n];你可以调整它的大小它不会像普通数组那样衰减为指针。
使用上面提到的标准库类型来避免数组退化为指针。如果使用相同的特性集,将节省调试时间,并且性能与普通数组完全相同。