Lets say I have a linked list which contains the following:
1, 2, 4, 5, 6, 2, 3, 2
now lets say I wish to convert this to:
1, 10, 2, 4, 5, 6, 10, 2, 3, 10, 2
i.e. insert 10 before all 2's.
How should I do this?
Off the top of my head
for (std::list<int>::iterator i = l.begin(); i != l.end(); ++i)
if (*i == 2)
l.insert(i, 10);
Simple enough. You don't need to worry about iterator invalidation because insert on a std::list does not invalidate any iterators. It's one of the advantages of using std::list.
Maybe something like this:
auto it = l.begin();
while ((it = std::find(it, l.end(), 2)) != l.end())
{
it = l.insert(it, 10);
std::advance(it, 2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With