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.

  • 相关阅读:
    linux系统之tr命令
    Tmux会话-基本操作及原理
    [题解] P1552 [APIO2012]派遣
    数论学习笔记
    Splay 学习笔记
    SpringCloud---入门篇(1)
    获小黄杉有感
    2020湖湘杯-CRYPTO-简单的密码3 WriteUp (CBC字节翻转)
    ECC椭圆曲线加密算法—加解密(SageMath实现)
    栅栏密码&W型栅栏密码-加解密(python实现)
  • 原文地址:https://www.cnblogs.com/berlin-sun/p/EffectiveSTL.html
Copyright © 2011-2022 走看看