将调用std :: vector.clear()也设置std :: vector.reserve()为零? [英] will a call to std::vector.clear() also set the std::vector.reserve() to zero?
问题描述
如果我在向量上使用.reserve(items),向量会为我猜测我需要的项目数量分配足够的内存。
如果我以后使用.clear(),会清除向量还是保存我早先定义的保留?
谢谢。
std :: vector< int& v1;
//以某种方式增加容量
std :: vector< int>()。swap(v1);
注意: 仍然得到upvote(因此人们读它),我觉得需要补充 C ++ 11 添加了 std :: vector< .. 。> :: shrink_to_fit()
,它请求向量去除未使用的容量。
If I use .reserve(items) on a vector, the vector will allocate enough memory for my guess of the number of items that I'll need.
If I later on use .clear(), will that just clear the vector or save my earlier defined reserve?
thanks.
It is specified that std::vector<T>::clear()
affects the size. It might not affect the capacity. For resetting the capacity, use the swap trick:
std::vector<int> v1;
// somehow increase capacity
std::vector<int>().swap(v1);
Note: Since this old answer is still getting upvotes (thus people read it), I feel the need to add that C++11 has added std::vector<...>::shrink_to_fit()
, which requests the vector to remove unused capacity.
这篇关于将调用std :: vector.clear()也设置std :: vector.reserve()为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!