迭代器first和last如果满足以下两点,则可以形成一个迭代器范围:1、它们指向同一个容器中的元素或超出末端的下一个位置;如果两个迭代器不相等,则对first反复应用自增加运算必须能够到达last,即,务必在使用前检查last绝对不能位于first之前。
使用迭代器时,通常可以编写程序使得要求迭代器有效的代码范围较短。然后,在该范围内,严格检查每一条语句,判断是否有元素增加或者删除,从而相应的调整迭代器的值。此外,任何insert、push、assign操作都会导致原迭代器失效。当编写循环将元素插入到vector或deque容器中时,程序必须确保迭代器在每次循环后都得到更新。
vector"int"
//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()){...}的检查,否则,上述四个语句的操作都是没有定义的。

No comments:
Post a Comment