list<T>::iterator tli = tlst.begin(); // Assume tlst.size() > 0 tlst.erase(tli); cout << *tli << endl; // Assume T::operator <<() is defined
c.end()
is the canonical invalid iterator - inherently invalid
list<T>::iterator tli1 = tlst.begin(); // Assume tlst.size() > 1 list<T>::iterator tli2 = tlst.end() - 1; tlst.erase(tlst.begin(), tlst.end()); cout << *tli1 << ", " *tli2 << endl; // Assume T::operator <<() is defined
vector<T>::iterator i = tvec.begin() + (tvec.end() - tvec.begin())/2; tvec.insert(i, v1); // i is now invalid tvec.insert(i, v2); // this has undefined behavior because i is invalid
vector<T>::iterator i1 = tvec.begin() + (tvec.end() - tvec.begin())/2; vector<T>::iterator i2 = i1 tvec.insert(i1, v1); // i1 and i2 are now invalid tvec.insert(i2, v2); // i1 and i2 are now invalid
i
is behind the invalidation point
i + 1
vector<T>::iterator i = tvec.begin() + (tvec.end() - tvec.begin())/2 - 1; tvec.insert(i + 1, v1); // i is still valid tvec.insert(i + 1, v2); // has defined behavior
*i,v2,v1
for (list<T>::iterator i = tlst.begin(); i != tlist.end(); i++) if (p(*i)) tlst.erase(i);
i
is invalid after the call to
erase()
, so i++
is undefined
for (list<T>::iterator i = tlst.begin(); i + 1 != tlist.end(); i++) if (p(*(i + 1))) tlst.erase(i + 1); if (p(*tlst.begin()) tlst.erase(tlst.begin());
for (set<T>::iterator i = tset.begin(); i + 1 != tset.end(); i++) if (p(*(i + 1))) tset.erase(i + 1); if (p(*i) tset.erase(i);
set<int>::iterator i = iset.begin(); while (true) { set<int>::iterator i2 = i; if (++i2 == iset.end()) break; if (odd(*i2)) iset.erase(i2); else i++; } if (odd(*iset.begin())) iset.erase(iset.begin());
ilist.erase(remove_if(ilist.begin(), ilist.end(), p), ilist.end());
tvec.insert( tvec.insert(tvec.begin() + (tvec.end() - tvec.begin())/2, v1), v2);
This page last modified on 3 August 2000.