Home > OS >  Why does Forward List's methods have "after" version, instead of using List's in
Why does Forward List's methods have "after" version, instead of using List's in

Time:02-24

insert, emplace, erase and splice from List, are replaced by insert_after, emplace_after, erase_after and splice_after in Forward List. Why is that?

*I understand the difference between the methods, I'm asking why do we need a different method to do those operations

CodePudding user response:

insert is defined as "insert before" for most containers, because end() iterator is defined as "one past the end". With insert() as "insert before", you can call it on whole range [begin(), end()], inclusive. If you defined insert() as "insert after", calling it on end() iterator would be Undefined Behaviour.

This however requires that container supports biderectional iterators, i.e. iterators that can be decremented. std::forward_list, to limit memory usage only supports forward iterators. With only forward iterator you cannot go back one element to insert before, so the only available operation is "insert after". It has the limitation that it cannot be called on end() iterator, but it's better than nothing.

  •  Tags:  
  • c
  • Related