July 1, 2010

Digest: container

将一个容器复制给另一个容器时,类型必须匹配:容器类型和元素类型都必须一致。

迭代器first和last如果满足以下两点,则可以形成一个迭代器范围:1、它们指向同一个容器中的元素或超出末端的下一个位置;如果两个迭代器不相等,则对first反复应用自增加运算必须能够到达last,即,务必在使用前检查last绝对不能位于first之前。

使用迭代器时,通常可以编写程序使得要求迭代器有效的代码范围较短。然后,在该范围内,严格检查每一条语句,判断是否有元素增加或者删除,从而相应的调整迭代器的值。此外,任何insert、push、assign操作都会导致原迭代器失效。当编写循环将元素插入到vector或deque容器中时,程序必须确保迭代器在每次循环后都得到更新。
vector"int"::iterator first = v.begin(); //cache begin iterator
//safer: recalaulate end on each trip whenever the loop adds/erases elements
while (first != v.end()) {  //do some processing in block...
     //insert new value, meanwhile update the first iterator
     first = v.insert(first, 42);
     ++first;    //advance first just past the element added just now
     }    //example ends
  
在调用front或back函数之前,或者在对begin或end返回的迭代器进行解引用运算之前,必须保证容器非空。例如,进行 if(!ilist.empty()){...}的检查,否则,上述四个语句的操作都是没有定义的。


如果程序要求随机访问元素,则应使用vector或deque容器;如果程序必须在容器中间位置插入或者删除元素,则应采用list容器。如果无法确定某种应用应当采取哪种容器,则编写代码时应尝试只使用vector和list容器都提供的操作:使用迭代器,而不是下表,并且避免随机访问元素。这样编写代码,在必要的时候,可以很方便将程序从使用vector修改为使用list容器。

No comments:

Post a Comment

Days of our lives

Daisypath Anniversary tickers