名前空間
変種
操作

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

提供: cppreference.com
< cpp‎ | container‎ | vector
 
 
 
 
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)... として転送されます。

新しい size()capacity() より大きい場合は、すべてのイテレータおよび参照 (終端イテレータも含む) が無効化されます。 そうでなければ、終端イテレータのみが無効化されます。

目次

[編集] 引数

args - 要素のコンストラクタに転送される引数
型の要件
-
T (コンテナの要素型)MoveInsertable および EmplaceConstructible の要件を満たさなければなりません。

[編集] 戻り値

(なし) (C++17未満)
挿入された要素を指す参照。 (C++17以上)

[編集] 計算量

償却定数時間。

[編集] 例外

例外が投げられた場合、この関数は何の効果も持ちません (強い例外保証)。 T のムーブコンストラクタが noexcept でなく、 *this に対して CopyInsertable でもない場合、 vector は例外を投げるムーブコンストラクタを使用します。 それが例外を投げた場合、保証は断��され、その効果は未規定になります。

ノート

再確保が行われるため、 emplace_back は vector に対しては要素型が MoveInsertable であることを要求します。

特殊化 std::vector<bool> には C++14 まで emplace_back() メンバがありませんでした。

[編集]

以下のコードは emplace_back を使用して President 型のオブジェクトを std::vector に追加します。 これは emplace_back がどのように引数を President のコンストラクタに転送するかをデモンストレーションし、 push_back を使用したときには必要な余計なコピーやムーブを回避するためにどのように emplace_back を使用するかを示します。

#include <vector>
#include <string>
#include <iostream>
 
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";
    elections.emplace_back("Nelson Mandela", "South Africa", 1994);
 
    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.

[編集] 関連項目

要素を末尾に追加します
(パブリックメンバ関数) [edit]