在我们的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++数组(即使用动态数组)。有一个问题是,你必须跟踪它们的大小,你需要手动删除它们,并做所有的家务工作。
我们还可以很容易地在向量中插入、推入和拉出值,这在数组中是不容易做到的。
如果我们讨论性能,那么如果你处理小的值,那么你应该使用数组,如果你处理大规模的代码,那么你应该使用向量(向量比数组更擅长处理大的值)。
其他回答
两者之间的性能差异很大程度上取决于实现——如果你比较一个实现得很差的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++代码。但是,请记住,在这种情况下,大多数赌注都是无效的,您将再次处理原始内存。
如果使用向量表示多维行为,则会对性能造成影响。
2d+向量会导致性能下降吗?
其要点是,每个子向量都有大小信息,因此会有少量开销,并且不一定会有数据序列化(与多维c数组不同)。这种串行化的缺乏可以提供比微优化更大的机会。如果你在做多维数组,最好扩展std::vector并滚动你自己的get/set/resize bits函数。
选择STL。没有性能损失。这些算法非常高效,它们在处理我们大多数人不会想到的细节方面做得很好。
为了回应Mehrdad说过的话:
然而,在某些情况下 你仍然需要数组。当 与低级代码(例如: 程序集)或旧的库 需要数组,您可能无法 用向量。
完全不是这样的。向量可以很好地降级为数组/指针,如果你使用:
vector<double> vector;
vector.push_back(42);
double *array = &(*vector.begin());
// pass the array to whatever low-level code you have
这适用于所有主要的STL实现。在下一个标准中,它将被要求工作(即使它现在做得很好)。
有时候数组确实比向量好。如果你总是在操纵别人 固定长度的对象集合,数组更好。考虑下面的代码片段:
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++)。