[英]Difference between these two methods of inputting elements of a vector? Which is more efficient?
Is the memory allocated to the vector dynamically in both cases or statically in 1st case and dynamically in 2nd? 在这两种情况下,是动态分配给矢量的内存还是在第一种情况下静态分配给矢量的内存?
1st 1
vector<int>::size_type n;
cin>>n;
vector<int> a(n);
for(vector<int>::size_type i=0;i<n;i++)
cin>>a[i];
2nd 第2
vector<int>::size_type n;
int temp;
cin>>n;
vector<int> a;
for(vector<int>::size_type i=0;i<n;i++)
{
cin>>temp;
a.push_back(temp);
}
Memory will be allocated dynamically (from heap) in both cases, but you will get only one allocation for first case and multiple reallocations in second. 在这两种情况下,都将动态地(从堆中)分配内存,但是对于第一种情况,您将仅获得一个分配,而在第二种情况中,将获得多个重新分配。 Actual number of reallocation in second case is somewhere between 1 and n.
第二种情况下的实际重新分配数量在1到n之间。
In both cases the memory for elements is allocated dynamically. 在这两种情况下,元素的内存都是动态分配的。 In the second case the memory reallocated almost each time when a new element is added.
在第二种情况下,几乎每次添加新元素时都会重新分配内存。 You could make these two cases equivalent if in the second case you would write
如果在第二种情况下,您可以将这两种情况等效
vector<int> a;
a.reserve( n );
在这两种情况下,都必须动态分配内存,因为在两种情况下都可以将更多元素添加到向量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.