C++ List Library - emplace() Function


Advertisements

Description

The C++ function std::list::emplace() extends list by inserting new element at a given position. This member function increase size of list.

Declaration

Following is the declaration for std::list::emplace() function form std::list header.

C++11

template <class... Args>
iterator emplace (const_iterator position, Args&&... args);

Parameters

  • position − Position in the list where the new element is to be inserted.

  • args − Arguments forwarded to construct the new element.

Return value

Returns a random access iterator which points to the newly emplaced element.

Exceptions

If reallocation fails bad_alloc exception is thrown.

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::list::emplace() function.

#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l = {3, 4, 5};

   auto it = l.emplace(l.begin(), 2);

   l.emplace(it, 1);

   cout << "List contains following element" << endl;

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

   return 0;
}

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

List contains following element in reverse order
1
2
3
4
5
list.htm
Advertisements