将调用std :: vector.clear()也设置std :: vector.reserve()为零? [英] will a call to std::vector.clear() also set the std::vector.reserve() to zero?

查看:576
本文介绍了将调用std :: vector.clear()也设置std :: vector.reserve()为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在向量上使用.reserve(items),向量会为我猜测我需要的项目数量分配足够的内存。



如果我以后使用.clear(),会清除向量还是保存我早先定义的保留?



谢谢。

std :: vector< T> :: clear()会影响大小。它可能不会影响容量。要重置容量,请使用 swap trick

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆