对std :: vector :: clear()的调用会将std :: vector :: capacity()设置为零吗? [英] Will a call to std::vector::clear() set std::vector::capacity() to zero?
问题描述
如果我在向量上使用.reserve(items),则向量将为我对我需要的项目数的猜测分配足够的内存。
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.
如果以后使用.clear(),会清除该向量还是保存我之前定义的储备?
If I later on use .clear(), will that just clear the vector or save my earlier defined reserve?
谢谢。
推荐答案
已指定 std :: vector< T> :: clear()
影响大小。它可能不会影响容量。要重置容量,请使用交换技巧:
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);
注意: 仍在投票(人们都读过),我觉得有必要补充一下, C ++ 11 已经添加了 std :: vector<。 。> :: shrink_to_fit()
,它请求向量删除未使用的容量。
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 :: capacity()设置为零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!