<std::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);
}