<分区>
我想知道哪个是一般用途最快的。因此,我们可以使用以下代码来代替 push_back() 数组。我认为数组更快,但我不确定。
int *p;
p = new int[5];
for(int i=0;i<5;i++)
*(p+i)=i;
// realloc
int* temp = new int[6];
std::copy(p, p + 5, temp);
delete [] p;
p = temp;
<分区>
我想知道哪个是一般用途最快的。因此,我们可以使用以下代码来代替 push_back() 数组。我认为数组更快,但我不确定。
int *p;
p = new int[5];
for(int i=0;i<5;i++)
*(p+i)=i;
// realloc
int* temp = new int[6];
std::copy(p, p + 5, temp);
delete [] p;
p = temp;
最佳答案
std::vector
的实现通常针对一般用途进行了优化。对于任何特定情况, native 数组的性能会更好或相等,但如果您事先不知道确切的使用特征, vector 通常会表现不错,并且比没有考虑过的 native 数组更好.例如,在上面的代码中,您明确地重新分配了内存,而 vector 实现可能已经分配了足够的内存(例如,使 vector 至少有一个缓存行)。
关于c++ - vector 与数组(速度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21611915/