<queue>
之间有什么区别?的安置和插入?
这里是关于 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);
}
关于c++ - <queue> 的 emplace 和 push 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35518611/