Effective STL 阅读笔记: Item 4 ~ 5: Call empty instead of checking size() against zero.


1 Item 4: Call empty instead of checking size() against zero

简而言之,用 container.size() 来检查 container 是否为空,而不要用 /container.size() == 0/。

原因: empty is a constant-time operation for all standard containers, but for some list implementations, size takes linear time.

2 Item 5: Prefer range member functions to their single-element counterparts

如果 Container 提供了区间成员函数 (Range member functions),尽量用它来替代自己写的循环和 algrithm 中的 copy 。

A range member function is a member function that, like STL algorithms, uses two iterator parameters to specify a range of elements over which something should be done.

Range member function 的好处在于:

  • 代码量更少,更清晰、直观。
  • 有可能会减少申请内存的次数, 减少数据的移动次数。

Range member function 适用的几种情况:

  1. 容器的构造: 所有标准容器都提供该方法:
    container::container(InputIterator begin, // Beginning of range
                         InputIterator end);  // End of range
  2. 区间插入: 所有标准容器都提供该方法:
    void container::insert(iterator      position, // where to insert the range
                           InputIterator begin,    // start of range to insert
                           InputIterator end);     // end of range to insert

    由于关联容器 (Associative Containers) 有自己的方法来计算插入的位置,insert 方法的第一个 参数经常可以省略:

    void container::insert(lnputIterator begin, InputIterator end);
  3. 区间删除 (Range Eraure):


    • Sequence Container:
      iterator container::erase(iterator begin, iterator end);
    • Associative Container:
      void container::erase(iterator begin, iterator end);
  4. 区间赋值 (Range Assignment): 所有 Container 均提供:
    void container::assign(lnputIterator begin, InputIterator end);
posted @ 2013-10-28 13:54  英超  Views(335)  Comments(0Edit  收藏  举报