c++queuestdpushemplace

Difference between <queue>'s emplace and push


What are the differences between <std::queue>'s emplace and push?

Here are explanations about the std::queue::emplace and std::queue::push .

Both methods add element after its current last element, return None.


Solution

  • push() adds a copy of an already constructed object into the queue as a parameter, it takes an object of the queue's element type.

    emplace() constructs a new object in-place at the end of the queue. It takes as parameters the parameters that the queue's element types constructor takes.

    If your usage pattern is one where you create a new object and add it to the container, you shortcut a few steps (creation of a temporary object and copying it) by using emplace().

    Example

    #include <iostream>
    #include <stack>
    using namespace std;
    
    struct Point_3D
    {
        int x, y, z;
        Point_3D(int x = 0, int y = 0, int z = 0)
        {
            this->x = x, this->y = y, this->z = z;
        }
    };
    
    
    int main()
    {
        stack<Point_3D> multiverse;
    
        // First, Object of that(multiverse) class has to be created, then it's added to the stack/queue
        Point_3D pt {32, -2452};
        multiverse.push(pt);
    
        // Here, no need to create object, emplace will do the honors
        multiverse.emplace(32, -2452);
    
        multiverse.emplace(455, -3);
        multiverse.emplace(129, 4, -67);
    }