std::inplace_vector<T,N>::try_emplace_back
template< class... Args >
constexpr std::optional<reference> try_emplace_back( Args&&... args );
|
(自C++26起) | |
条件将类型为 T 追加到容器末尾。
如果 size() == capacity() 为 true,则无效果。否则,将使用直接非列表初始化追加一个 std::forward<Args>(args)... 类型为 T。
没有迭代器或引用失效,除了 end(),在插入发生时失效。
参数
| args | - | 要转发给元素构造函数的参数 |
| 类型要求 | ||
-
T
必须能够从
std::
forward
<
Args
>
(
args
)
...
进行
就地构造
到
inplace_vector
中。
|
||
返回值
std:: addressof ( back ( ) ) 当 size ( ) < capacity ( ) 时,否则为 nullptr 。
复杂度
常量。
异常
任何由插入元素初始化抛出的异常。若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。
备注
| 此章节不完整 原因:解释此API的用途。 |
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_inplace_vector |
202603L |
(C++26) | 更好的返回类型(std::optional<reference>代替pointer)用于try_push_back和try_emplace_back
|
示例
#include <cassert>
#include <complex>
#include <inplace_vector>
#include <optional>
int main()
{
using namespace std::complex_literals;
using C = std::complex<double>;
using I = std::inplace_vector<C, 3>;
auto v = I{1.0 + 2.0i, 3.0 + 4.0i};
std::optional<C&> c = v.try_emplace_back(5.0, 6.0);
assert(*c == 5.0 + 6.0i);
assert((v == I{1.0 + 2.0i, 3.0 + 4.0i, 5.0 + 6.0i}));
c = v.try_emplace_back(7.0, 8.0); // no space => no insertion
assert(c == std::nullopt);
assert((v == I{1.0 + 2.0i, 3.0 + 4.0i, 5.0 + 6.0i}));
}
参见
|
在末尾就地构造元素
(公开成员函数) |
|
|
在末尾添加元素
(公开成员函数) |
|
|
在末尾添加元素范围
(公开成员函数) |
|
|
尝试在末尾添加元素范围
(公开成员函数) |
|
|
无条件在末尾就地构造元素
(公开成员函数) |
|
|
无条件在末尾添加元素
(公开成员函数) |
|
|
移除末尾元素
(公开成员函数) |
|
|
创建从参数推断类型的
std::back_insert_iterator
(函数模板) |