c++ - Validity of std::prev and std::next for std::list -


i storing iterator list:

list<int> l; l.push_back(21); l.push_back(1); l.push_back(31); l.push_back(41);  auto = l.find(21); 

in algorithm, whenever delete node, need add adjoining elements. this:

auto prev = std::prev(it); auto next = std::next(it); *prev = *prev + *next; l.erase(it); 

as see, need ensure boundary conditions. values std::prev() , std::next() return if:

  • they first , last elements;
  • or if it has become invalid @ point?

what values std::prev() , std::next() return...

they return nth (where n defaults 1) predecessor or successor of iterator it. see here [iterator.operations] /6 , /7.

... if first , last elements; or if it has become invalid @ point?

the iterator needs valid before call made. return value invalid iterator if it 1 of corresponding boundary iterators; i.e. it == begin() prev(it) , it == end() next(it).

the validity of it needs established before used argument prev() or next(). std::prev() , std::next() have no why of determining if iterator decrement or increment put iterator outside bounds of container.

as such, sounds need code 2 boundary conditions in erase part of algorithm; first it == l.begin() , second it == prev(l.end()), , possibly third if element not found (hence it == l.end()).

// proceed found... if (it != l.end()) {   if (it == l.begin()) {     // nothing do...? element removed first 1   }   else if (it == std::prev(l.end()) {     // nothing? element removed last one....   }   else {     auto prev = std::prev(it);     auto next = std::next(it);     *prev = *prev + *next;   }   l.erase(it); // remove found element... } 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo