###《Effective STL》--Chapter1

时间:2023-03-08 22:03:32

点击查看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++;
    }
    }