[英]Difference between <queue>'s emplace and push
<queue>
的 emplace 和 push 有什么区别?
这是关于std::queue::emplace和std::queue::push的解释。
两种方法都在当前最后一个元素之后添加元素,返回None
。
push()
将已构造对象的副本作为参数添加到队列中,它采用队列元素类型的对象。
emplace()
在队列末尾就地构造一个新对象。 它将队列的元素类型构造函数采用的参数作为参数。
如果您的使用模式是创建一个新对象并将其添加到容器中,您可以使用emplace()
。
#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.