C++之Effective STL学习笔记Item14

使用reserve来避免不必要的重新分配!

The reserve member function allows you to minimize the number ofreallocations that must be performed, thus avoiding the costs of reallocationand iterator/pointer/reference invalidation.

使用size函数获取容器中的元素个数,使用capacity函数获取容器已分配的内容可以存储元素的个数。

对应上述两个函数:resizereserve分别用来改变上述两个值。

Create a vector<int> holding thevalues 1–1000.

Without using reserve, you might do it like this:

1 vector<int> v;
2 for (int i = 1; i <= 1000; ++i) v.push_back(i);

This code will typically result in between two and 18 reallocations during the course of the loop.  

 1 vector<int> v;
 2 int changeNum = 0;
 3 int cap = v.capacity();
 4 for (int i = 1; i <= 1000; ++i)
 5 {
 6     v.push_back(i);
 7     if (cap != v.capacity())
 8     {
 9         cap = v.capacity();
10         changeNum++;
11     }
12 }                                  //Yes, the changeNum is 18!

Modify the code to use reserve gives us this:

1 vector<int> v;
2 v.reserve(1000);
3 for (int i = 1; i <= 1000; ++i) v.push_back(i);

There are two common ways to use reserve to avoid unneeded reallocations. The first is applicable when you know exactly or approximately how many elements will ultimately end up in your container. The second way is to reserve the maximum space you could ever need, then, once you’ve added all your data, trim off any excess capacity.

转载于:https://www.cnblogs.com/berlin-sun/p/EffectiveSTL.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值