名稱空間
變體
操作

std::deque<T,Allocator>::emplace_back

來自 cppreference.com
< cpp‎ | 容器‎ | deque
 
 
 
 
template< class... Args >
void emplace_back( Args&&... args );
(C++11 起)
(C++17 前)
template< class... Args >
reference emplace_back( Args&&... args );
(C++17 起)

在容器末尾新增一個新元素。該元素透過 std::allocator_traits::construct 構造,它通常使用 placement-new 在容器提供的位置原地構造元素。引數 args... 被轉發給建構函式作為 std::forward<Args>(args)...

所有迭代器(包括 end() 迭代器)都將失效。無引用失效。

目錄

[編輯] 引數

args - 轉發給元素建構函式的引數
型別要求
-
T (容器的元素型別) 必須滿足 EmplaceConstructible 的要求。

[編輯] 返回值

(無)

(C++17 前)

對插入元素的引用。

(C++17 起)

[編輯] 複雜度

常數時間。

[編輯] 異常

如果由於任何原因丟擲異常,此函式無效果(強異常安全保證)。


[編輯] 示例

以下程式碼使用 emplace_backPresident 型別的物件附加到 std::deque。它演示了 emplace_back 如何將引數轉發給 President 建構函式,並展示了使用 emplace_back 如何避免使用 push_back 時所需的額外複製或移動操作。

#include <deque>
#include <cassert>
#include <iostream>
#include <string>
 
struct President
{
    std::string name;
    std::string country;
    int year;
 
    President(std::string p_name, std::string p_country, int p_year)
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
    {
        std::cout << "I am being constructed.\n";
    }
 
    President(President&& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    {
        std::cout << "I am being moved.\n";
    }
 
    President& operator=(const President& other) = default;
};
 
int main()
{
    std::deque<President> elections;
    std::cout << "emplace_back:\n";
    auto& ref = elections.emplace_back("Nelson Mandela", "South Africa", 1994);
    assert(ref.year == 1994 && "uses a reference to the created object (C++17)");
 
    std::deque<President> reElections;
    std::cout << "\npush_back:\n";
    reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));
 
    std::cout << "\nContents:\n";
    for (President const& president: elections)
        std::cout << president.name << " was elected president of "
                  << president.country << " in " << president.year << ".\n";
 
    for (President const& president: reElections)
        std::cout << president.name << " was re-elected president of "
                  << president.country << " in " << president.year << ".\n";
}

輸出

emplace_back:
I am being constructed.
 
push_back:
I am being constructed.
I am being moved.
 
Contents:
Nelson Mandela was elected president of South Africa in 1994.
Franklin Delano Roosevelt was re-elected president of the USA in 1936.

[編輯] 參閱

新增元素到結尾
(公共成員函式) [編輯]
(C++11)
就地構造元素
(公共成員函式) [編輯]