std::deque<T,Allocator>::emplace_back
提供: cppreference.com
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)... として転送されます。
すべてイテレータ (終端イテレータも含む) が無効化されます。 参照は無効化されません。
目次 |
[編集]引数
args | - | 要素のコンストラクタに転送される引数 |
型の要件 | ||
-T (コンテナの要素型) は EmplaceConstructible の要件を満たさなければなりません。 |
[編集]戻り値
(なし) | (C++17未満) |
挿入された要素を指す参照。 | (C++17以上) |
[編集]計算量
一定。
[編集]例外
例外が投げられた場合、この関数は何の効果も持ちません (強い例外保証)。
[編集]例
以下のコードは emplace_back
を使用して President
型のオブジェクトを std::deque に追加します。 これは emplace_back
がどのように引数を President
のコンストラクタに転送するかをデモンストレーションし、 push_back
を使用したときには必要な余計なコピーやムーブを回避するためにどのように emplace_back
を使用するかを示します。
Run this code
#include <deque>#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::deque<President> elections;std::cout<<"emplace_back:\n"; elections.emplace_back("Nelson Mandela", "South Africa", 1994); 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.
[編集]関連項目
要素を末尾に追加します (パブリックメンバ関数) |