Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we insert into a stl list while traversing

Tags:

c++

stdlist

I have a list of items which I am traversing. While traversing new items get created and they should be inserted at different appropriate positions of the same list.

I am using std::list as its insertion time (ordered) is log(N).

Can this cause any issues as I am using an iterator to the container while inserting into the same? Note that insertion can happen just next to current iterator position too.

If this does not work, what are the other options that I have? Do we have a design pattern or a best practice for this kind of activity?

like image 252
sujeewa Avatar asked Nov 08 '25 17:11

sujeewa


2 Answers

Yes, you can insert into a given position in a list given its iterator, using list::insert.

The following will insert the value 3 as the second item in the list:

list<int> stuff(/*...*/);
auto it = stuff.begin();
++it;
stuff.insert (it,3);

Specifically, the list::insert function inserts an item just before the iterator that's passed to it. This is the most common way to insert into a list.

Note, however, that std::list's insertion time is not O(log(n)). The complexity of inserting one element into a std::list, at any position (given an iterator), is O(1).

like image 110
IanPudney Avatar answered Nov 10 '25 08:11

IanPudney


Inserting into a std::list doesn't invalidate any iterator or reference.

In C++'s STL, when an operation is said to don't invalidate any iterator or reference, means that it is safe to continue working with the same iterator after the operation, or any copy of previous or next iterators of the same container.

like image 31
Peregring-lk Avatar answered Nov 10 '25 09:11

Peregring-lk