###《Effective STL》--Chapter1

本文介绍了C++标准库中容器的高效使用技巧,包括如何选择正确的容器操作方法、使用区间成员函数提高性能以及注意事项等。

点击查看Evernote原文

#@author:       gr
#@date:         2014-09-12
#@email:        forgerui@gmail.com

Chapter1 容器

Topic 4: 调用empty而不是检查size()是否为0

  当检查一个容器是否为空时,要使用empty而不是size()empty在检查时的时间总是常数的,而对于size(),一些容器的实现可能是线性的(如list)。

Topic 5: 区间成员函数优先于与之对应的单元素成员函数

  使用区间成员函数会得到更高的效率,其次,在可读性方面,使用区间成员函数也比自己写循环要好看多了。

  • 区间创建

      container::container(InputIterator begin, InputIterator end);
  • 区间插入

      //序列容器
      void container::insert(iterator position, InputIterator begin, InputIterator end);
    
      //关联容器
      void container::insert(InputIterator begin, InputIterator end);
  • 区间删除

      //序列容器
      iterator container::erase(iterator begin, iterator end);
    
      //关联容器
      void container::erase(iterator begin, iterator end);
  • 区间赋值

      void container::assign(InputIterator begin, InputIterator end);
Topic 9: 慎重选择删除元素的方法
  • 要删除容器中有特定值的所有对象
    如果容器是vector,stringdeque,则使用erase-remove用法。

      //删除vector<int>中所有值为10的元素
      c.erase(remove(c.bgein(), c.end(), 10), c.end());

    如果容器是list,则使用list::remove

      l.remove(l.begin(), l.end(), 10);

    如果容器是一个标准关联容器,则使用它的erase成员函数。

      //删除关联容器中值为10的元素
      m.erase(10);
  • 在循环内删除某些元素
    序列容器使用返回值更新迭代器。

      while(it != con.end()){
          if (it->getCount() > theshold){
              it = con.erase(it);
          }else{
              it++;
          }
      }

    关联容器对迭代器递增操作。

      while (it != con.end()){
          if (it->getCount() > threshold){
              con.erase(it++);
          }else{
              it++;
          }
      }

转载于:https://www.cnblogs.com/gr-nick/p/3977009.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值