zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    1365 Fib(N) mod Fib(K) [斐波那契相关]
    51nod1439 互质对 [莫比乌斯函数, 容斥]
    UVA1642 魔法GCD Magical GCD [gcd, 双向链表]
    李超线段树学习笔记 [模板]
    P4297 [NOI2006]网络收费 [树形dp]
    田忌赛马 [贪心(完成) / 动态规划(待填坑)]
    菌落 [状压dp?]
    异或约数和 [异或相关]
    java 驼峰命名
    java 静态构造函数
  • 原文地址:https://www.cnblogs.com/berlin-sun/p/EffectiveSTL.html
Copyright © 2011-2022 走看看