C++ Deque Library - insert() Function



Description

The C++ function std::deque::insert() extends container by inserting new element at position in deque. 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++98

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

C++11

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

Parameters

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

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

Return value

Returns a random access 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> d = {3, 4, 5};

   auto it = d.insert(d.begin(), 2);
   d.insert(it, 1);

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

   for (auto it = d.begin(); it != d.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