33,311
社区成员
发帖
与我相关
我的任务
分享
while(first!=v.end())
first=v.insert(first,42);
++first;
//如果我们尝试通过存储 end() 操作返回的迭代器来“优化”该循环,将导致灾难性错误:
vector<int>::iterator first = v.begin(),
last = v.end(); // cache end iterator
// diaster: behavior of this loop is undefined
while (first != last) {
// do some processing
// insert new value and reassign first, which otherwise would be invalid
first = v.insert(first, 42);
++first; // advance first just past the element we added
}
//上述代码的行为未定义。在很多实现中,该段代码将导致死循环。
while(first!=v.end())
first=v.insert(first,42);
first += 2;