|
iterator insert ( iterator position, const T& x );
void insert ( iterator position, size_type n, const T& x );
template <class InputIterator>
void insert ( iterator position, InputIterator first, InputIterator last );
Insert elements
The deque container is extended by inserting new elements before the element at the specified position.
This effectively increases the container size by the amount of elements inserted, and invalidates all the previouly obtained iterators, although if the insertion is on either the beginning or the end, references remain valid.
Double-ended queues are designed to be efficient performing insertions (and removals) from either the end or the beginning of the sequence. Insertions on other positions are usually less efficient than in list containers.
The parameters determine how many elements are inserted and to which values they are initialized:
Parameters
- position
- Position in the container where the new elements are inserted.
iterator is a member type, defined as a random access iterator type.
- x
- Value to be used to initialize the inserted elements.
T is the first template parameter (the type of the elements stored in the container).
- n
- Number of elements to insert. Each element is initialized to the value specified in x.
Member type size_type is an unsigned integral type.
- first, last
- Iterators specifying a range of elements. Copies of the elements in the range [first,last) are inserted at position position.
Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
The template type can be any type of input iterator.
Return value
Only the first version returns a value, which is an iterator that points to the newly inserted element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
// inserting into a deque
#include <iostream>
#include <deque>
#include <vector>
using namespace std;
int main ()
{
deque<int> mydeque;
deque<int>::iterator it;
// set some initial values:
for (int i=1; i<6; i++) mydeque.push_back(i); // 1 2 3 4 5
it = mydeque.begin();
++it;
it = mydeque.insert (it,10); // 1 10 2 3 4 5
// "it" now points to the newly inserted 10
mydeque.insert (it,2,20); // 1 20 20 10 2 3 4 5
// "it" no longer valid!
it = mydeque.begin()+2;
vector<int> myvector (2,30);
mydeque.insert (it,myvector.begin(),myvector.end());
// 1 20 30 30 20 10 2 3 4 5
cout << "mydeque contains:";
for (it=mydeque.begin(); it<mydeque.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
|
Output:
mydeque contains: 1 20 30 30 20 10 2 3 4 5
|
Complexity
Linear on the number of elements inserted (copy construction). Plus, depending on the particular library implemention, additional linear time in up to the number of elements between position and one of the ends of the deque.
See also
deque::splicedeque::merge
|