std::vector<T,Allocator>::emplace_back
来自 cppreference.cn
template< class... Args > void emplace_back( Args&&... args ); |
(since C++11) (until C++17) |
|
template< class... Args > reference emplace_back( Args&&... args ); |
(since C++17) (constexpr since C++20) |
|
在容器末尾追加新元素。元素通过 std::allocator_traits::construct 构造,通常使用 placement-new 在容器提供的位置就地构造元素。参数 args... 作为 std::forward<Args>(args)... 转发给构造函数。
如果在操作后新的 size()
大于旧的 capacity()
,则会发生重分配,在这种情况下,所有迭代器(包括 end()
迭代器)和对元素的所有引用都将失效。否则,只有 end()
迭代器失效。
目录 |
[编辑] 参数
args | - | 转发给元素构造函数的参数 |
类型要求 | ||
-T (容器的元素类型)必须满足 MoveInsertable 和 EmplaceConstructible 的要求。 |
[编辑] 返回值
(无) |
(until C++17) |
指向插入元素的引用。 |
(since C++17) |
[编辑] 复杂度
均摊常数。
[编辑] 异常
如果由于任何原因抛出异常,此函数不起作用(强异常安全保证)。如果 T
的移动构造函数不是 noexcept 并且不能 CopyInsertable 到 *this 中,则 vector
将使用抛出异常的移动构造函数。如果它抛出异常,则保证被放弃,并且效果未指定。
注解
由于可能发生重分配,emplace_back
要求向量的元素类型为 MoveInsertable。
[编辑] 示例
以下代码使用 emplace_back
将 President
类型的对象追加到 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.
[编辑] 参见
在末尾添加元素 (公共成员函数) | |
(C++11) |
就地构造元素 (公共成员函数) |