std::vector emplace() 方法
- 自 C++20 起
- 自 C++11 起
// prism-push-types:iterator,const_iterator
// Non const version only
template< class... Args >
constexpr iterator emplace( const_iterator pos, Args&&... args );
// prism-push-types:iterator,const_iterator
// Non const version only
template< class... Args >
iterator emplace( const_iterator pos, Args&&... args );
在 `pos` 之前直接将一个新元素插入到容器中。
该元素通过 `std::allocator_traits
参数 `args...` 作为 `std::forward
参数
- `pos` - 新元素将被构造的迭代器位置
args
- 转发给元素构造函数的参数
类型要求
- `T`(容器的元素类型)必须满足 `MoveAssignable`、`MoveInsertable` 和 `EmplaceConstructible` 的要求。
返回值
指向插入元素的迭代器
复杂度
与 `pos` 到容器末尾的距离呈线性关系 - O(std::distance(pos, end()))。
异常
如果除了值类型的拷贝构造函数、移动构造函数、赋值运算符或移动赋值运算符之外抛出异常,
或者在使用 `emplace()` 在末尾插入单个元素时抛出异常,并且值类型是 `CopyInsertable` 或 nothrow 可移动构造的,则没有副作用(强异常保证)。
否则,效果未指定.
示例
#include <iostream>
#include <string>
#include <vector>
struct A {
std::string s;
A(std::string str) : s(std::move(str)) { std::cout << " constructed\n"; }
A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; }
A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; }
A& operator=(const A& other) {
s = other.s;
std::cout << " copy assigned\n";
return *this;
}
A& operator=(A&& other) {
s = std::move(other.s);
std::cout << " move assigned\n";
return *this;
}
};
int main()
{
std::vector<A> container;
// reserve enough place so vector does not have to resize
container.reserve(10);
std::cout << "construct 2 times A:\n";
A two { "two" };
A three { "three" };
std::cout << "emplace:\n";
container.emplace(container.end(), "one");
std::cout << "emplace with A&:\n";
container.emplace(container.end(), two);
std::cout << "emplace with A&&:\n";
container.emplace(container.end(), std::move(three));
std::cout << "content:\n";
for (const auto& obj : container)
std::cout << ' ' << obj.s;
std::cout << '\n';
}
construct 2 times A:
constructed
constructed
emplace:
constructed
emplace with A&:
copy constructed
emplace with A&&:
move constructed
content:
one two three