名稱空間
變體
操作

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

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

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

如果操作後新的 size() 大於舊的 capacity(),則會發生重新分配,在這種情況下,所有迭代器(包括 end() 迭代器)以及所有對元素的引用都將失效。否則,只有 end() 迭代器會失效。

目錄

[編輯] 引數

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

[編輯] 返回值

(無)

(C++17 前)

對插入元素的引用。

(C++17 起)

[編輯] 複雜度

攤還常數時間。

[編輯] 異常

如果由於任何原因丟擲異常,此函式不產生任何效果(強異常安全保證)。如果 T 的移動建構函式不是 noexcept 且不可 CopyInsertable*thisvector 將使用丟擲異常的移動建構函式。如果它丟擲異常,則保證失效,並且效果未指定。

注意

由於可能發生重新分配,emplace_back 要求元素的型別對於 vector 是 MoveInsertable 的。

[編輯] 示例

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

#include <vector>
#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::vector<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::vector<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.

[編輯] 參閱

新增元素到結尾
(public member function) [編輯]
(C++11)
就地構造元素
(public member function) [編輯]