How do I insert()
a bunch of items to the middle of a deque
in linear time?
(The items I am inserting are not accessible through an STL-style iterator.)
How do I insert()
a bunch of items to the middle of a deque
in linear time?
(The items I am inserting are not accessible through an STL-style iterator.)
Call the insert method that takes a sequence of items to insert, see the 3rd method listed here:
http://msdn.microsoft.com/en-us/library/zcww84w5(v=vs.71).aspx
And, create your own STL-style iterator to access the items you want to insert. See:
Custom Iterator in C++
Add all the elements after the insertion point to a vector.
Remove all elements after insertion point.
Append new range to deque.
Append vector to deque.
This is O(2n) worst case, instead of O(n^2).
There is a
deque::insert(iterator pos, const T&x)
function taking the positionpos
asdeque::iterator
and a single element. Using this method you could insert all elements one by one.pos
can easily be obtained (if you have an index before which you want to insert the element) bydeque.begin()+index
. Theinsert
method returns an iterator for the newly inserted element, simply increment this returned iterator to get the next position:This however cantake
O(n*k)
time, since insertion of a single element is (iirc) a linear time operation iirc.The second overload is
deque::insert(iterator pos, InputIterator f, InputIterator l)
: Remember that simple pointers also fulfill the requirements of an STL input iterator, so if you have a C-Style arrayT array[]
of lengthn
containing your elements, you could insert all elements from this array withThis operation can be carried out in linear time, i.e.
O(n+k)
. I'm not sure if this is guaranteed by the standard, but I suppose that most implementation will do it efficiently.EDIT
I quickly checked with Microsoft's implementation, they do it by a sequence of either
push_back
orpush_front
, whatever is closer topos
and then rotating the elements to their final place, which guarantees the aboveO(n+k)
complexity. Of course, that could also be done "by hand" like:(I copied the code from Microsofts implementation of
deque::insert
, removing debug code and exception handling,Input:
Deque: lengtl = l,
New items (m = number of new items)
Algo:
create a new deque (1)
Copy all items from original deque until where you want to insert the new ones (p)
Add new items (m)
Add items from old deque (m-p)
Maybe you can just use the new deque but at worst:
Copy new deque onto old one (after a complete clear: ):
Cost (l+m)
The worst cost is thus: origsize * 2 + newitems which is linear.
The "clear deck" isn't counted here but it is also linear ( at worst).