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.

  • 相关阅读:
    第16章 Java内存模型
    第15章 原子变量与非阻塞同步机制
    第14章 构建自定义的同步工具
    第13章 显式锁
    第12章 并发程序的测试
    第11章 性能与可伸缩性
    第10章避免活跃性危险
    第8章 线程池的使用
    JDBC工具类——JdbcUtils(6)
    JDBC工具类——JdbcUtils(5)
  • 原文地址:https://www.cnblogs.com/berlin-sun/p/EffectiveSTL.html
Copyright © 2011-2022 走看看