c++ - <queue> 的 emplace 和 push 的区别

标签 c++ queue push emplace

<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/

相关文章:

Javascript 数组多维推送?

c++ - 如何解决 C++ 命名空间和全局函数之间的名称冲突?

c++ - checkstyle 等同于 C++?

c++ - vector 中元素的默认构造

javascript - 使用 Javascript 推送嵌套数组注释

git subtree push --squash 不压缩

c++ - 无法使用 socat 写入打开 QSerialPort

php - 用 PHP 和 MySQL 实现一个简单的队列?

c# - 反转队列

mysql - 将多个 SQL 查询作为一个字符串排队,服务器行为?