std::inplace_vector<T,N>::emplace_back
来自 cppreference.cn
template< class... Args > constexpr reference emplace_back( Args&&... args ); |
(since C++26) | |
将新元素追加到容器的末尾。通常,元素是使用 placement-new 在容器提供的位置就地构造的。参数 args... 作为 std::forward<Args>(args)... 转发到构造函数。
迭代器或引用均不会失效,除了 end()
,如果发生插入,则 end()
会失效。
目录 |
[编辑] 参数
args | - | 转发给元素构造函数的参数 |
类型要求 | ||
-T 必须满足 EmplaceConstructible 的要求。 |
[编辑] 返回值
back()
,即对插入元素的引用。
[编辑] 复杂度
常数。
[编辑] 异常
- std::bad_alloc 如果调用前 size() == capacity()。
- 插入元素初始化抛出的任何异常。
如果由于任何原因抛出异常,这些函数将不起作用(强异常安全保证)。
[编辑] 示例
运行此代码
#include <inplace_vector> #include <new> #include <print> #include <string> #include <utility> int main() { std::inplace_vector<std::pair<std::string, std::string>, 2> fauna; std::string dog{"\N{DOG}"}; fauna.emplace_back("\N{CAT}", dog); fauna.emplace_back("\N{CAT}", std::move(dog)); std::println("fauna = {}", fauna); try { fauna.emplace_back("\N{BUG}", "\N{BUG}"); // throws: there is no space } catch(const std::bad_alloc& ex) { std::println("{}", ex.what()); } std::println("fauna = {}", fauna); }
可能的输出
fauna = [("🐈", "🐕"), ("🐈", "🐕")] std::bad_alloc fauna = [("🐈", "🐕"), ("🐈", "🐕")]
[编辑] 参见
将一系列元素添加到末尾 (public member function) | |
将一个元素添加到末尾 (public member function) | |
尝试将一个元素添加到末尾 (public member function) | |
尝试在末尾就地构造一个元素 (public member function) | |
尝试将一系列元素添加到末尾 (public member function) | |
无条件地将一个元素添加到末尾 (public member function) | |
无条件地在末尾就地构造一个元素 (public member function) | |
移除最后一个元素 (public member function) | |
创建从参数推断类型的 std::back_insert_iterator (function template) |