C++ Deque Library - insert() Function



Description

The C++ function std::deque::insert() extends deque by inserting new element in the container. If reallocation happens storage requirement for this container is fulfilled by internal allocator.

Declaration

Following is the declaration for std::deque::insert() function form std::deque header.

C++11

iterator insert (const_iterator position, value_type&& val);

Parameters

  • position − Index in the deque where new element to be inserted.

  • value − Value to be assigned to newly inserted element.

Return value

Returns an iterator which points to the newly inserted element.

Exceptions

If reallocation fails bad_alloc exception is thrown.

Time complexity

Linear i.e. O(n)

Example

The following example shows the usage of std::deque::insert() function.

#include <iostream>
#include <deque>

using namespace std;

int main(void) {

   deque<int> d1 = {1, 2, 3, 4, 5};
   deque<int> d2;

   for (int i = 0; i < d1.size(); ++i)
      d2.insert(d2.begin() + i, move(*(d1.begin() + i)));

   cout << "Content of deque are" << endl;

   for (auto it = d2.begin(); it != d2.end(); ++it)
      cout << *it << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Content of deque are
1
2
3
4
5
deque.htm
Advertisements