C++ Stack Library - emplace() Function



Description

The C++ function std::stack::emplace() constructs and inserts new element at the top of stack. New element is inserted in a place i.e. without performing copy or move operation.

Declaration

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

C++11

template <class... Args> 
void emplace (Args&&... args);

Parameters

args − Arguments forwarded to construct the new elements

Return value

None

Exceptions

Depends upon underlying container.

Time complexity

Constant i.e. O(1)

Example

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

#include <iostream>
#include <stack>

using namespace std;

int main(void) {
   stack<int> s;

   for (int i = 0; i < 5; ++i)
      s.emplace(i + 1);

   while (!s.empty()) {
      cout << s.top() << endl;
      s.pop();
   }

   return 0;
}

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

Stack contents are
5
4
3
2
1
stack.htm
Advertisements