簡體   English   中英

之間的區別<queue>的就位和推動

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

<queue>的 emplace 和 push 有什么區別?

這是關於std::queue::emplacestd::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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM