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?
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: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 astd::list
, at any position (given an iterator), is O(1).