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.

  • 相关阅读:
    Java修饰符
    java中接口的定义
    抽象类
    final关键字的特点
    hdu6489 2018 黑龙江省大学生程序设计竞赛j题
    POJ 3268 (dijkstra变形)
    poj 2253 floyd最短路
    poj1681 Network
    bzoj1202 狡猾的商人
    Nastya Is Buying Lunch
  • 原文地址:https://www.cnblogs.com/berlin-sun/p/EffectiveSTL.html
Copyright © 2011-2022 走看看