Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Insert before" for std::list

Tags:

c++

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?

like image 434
Baz Avatar asked Mar 08 '26 21:03

Baz


2 Answers

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.

like image 51
john Avatar answered Mar 10 '26 12:03

john


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);
}
like image 24
Some programmer dude Avatar answered Mar 10 '26 11:03

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!