简体   繁体   English

之间的区别<queue>的就位和推动

[英]Difference between <queue>'s emplace and push

What are the differences between <queue> 's emplace and push? <queue>的 emplace 和 push 有什么区别?

here's explanation about the std::queue::emplace and std::queue::push .这是关于std::queue::emplacestd::queue::push的解释。

Both methods add element after its current last element, return None .两种方法都在当前最后一个元素之后添加元素,返回None

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. push()将已构造对象的副本作为参数添加到队列中,它采用队列元素类型的对象。

emplace() constructs a new object in-place at the end of the queue. emplace()在队列末尾就地构造一个新对象。 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() .如果您的使用模式是创建一个新对象并将其添加到容器中,您可以使用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM