Home » C++ Stack emplace() Function

C++ Stack emplace() Function

by Online Tutorials Library

C++ Stack emplace() Function

C++ Stack emplace() function adds a new element at the top of the stack above the current top element. Now, we have a stack with already existing elements, and we wish to insert or push a new element in the stack, for doing that we use this function.

Syntax

Parameters

args:The parameter forwards the argument for the construction of new element. That is the element specified by args is inserted in the stack over the current top element. The newly inserted element now becomes the top element and all the push and pop operations are performed on it.

Return value

The function is used only for the addition of new elements and does not return any value. Hence the return type of the function is void.

Example 1

//The program illustrates the use of emplace function by adding two simple strings at the top of the stack and printing them.

Output:

Contents of newstack:  I am the second one  I am the first line  

Example 2

//The program illustrates the use of emplace function by inserting the table of 11 on the and then respectively printing it.

Output:

Contents of newstack:   Table of 11121  99  88  77  66  55  44  33  22  11  

Example 3

//The program illustrates the use of emplace function by adding two simple strings at the top of the stack and printing them.

Output:

The function adds new elements are the top of the stack           We are here to see the application use of emplace function in stacks   

Complexity

One call is made to the emplace_back. The function is used for inserting a new element which is done by making a single call.

Data races

All the elements present in the stack are modified. Since the element is added to the top hence respective positions of all the other elements are also changed.

Exception Safety

Guarantee as equivalent to the operations that are performed on the underlying container object is provided.

Next TopicC++ Stack

You may also like