std::deque<T,Allocator>::emplace_back
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 构造,它典型地用布置 new 于容器所提供的位置原位构造元素。参数 args...
以 std::forward<Args>(args)... 转发到构造函数。
所有迭代器,包含尾后迭代器,都被非法化。没有引用被非法化。
参数
args | - | 转发到元素构造函数的参数 |
类型要求 | ||
-value_type 必须满足可就位构造 (EmplaceConstructible) 的要求。
|
返回值
(无) |
(C++17 前) |
到被插入元素的引用。 |
(C++17 起) |
复杂度
常数。
异常
若抛出异常,则此函数无效果(强异常保证)。
示例
下列代码用 emplace_back
后附 President
类型对象到 std::deque 。它演示 emplace_back
如何转发参数到 President
的构造函数,并展示如何用 emplace_back
避免用 push_back
时的额外复制或移动操作。
运行此代码
#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.
参阅
将元素添加到容器末尾 (公开成员函数) |