在线文档教程
C++
容器 | Containers

std::vector::emplace_back

STD::载体::Emplace[医]背

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)

将一个新元素附加到容器的末尾。元素是通过std::allocator_traits::construct,它通常使用Plant-New来在容器提供的位置构造就地元素。争论args...被转发给构造函数的std::forward<Args>(args)......

如果新的size()大于capacity()然后,所有迭代器和引用%28,包括过去-结束迭代器%29无效。否则,只有过去结束迭代器无效。

参数

args-arguments to forward to the constructor of the element

类型要求

-T%28容器%27s元素类型%29必须满足MoveInsertable和EmplaceConstrucable的要求。

返回值

(none)(until C++17)
A reference to the inserted element.(since C++17)

复杂性

摊销常数

例外

如果引发异常,则此函数不具有%28强异常保证%29的效果。如果T%27移动构造函数不是noexcept而不是CopyInsertable*this,向量将使用抛出的移动构造函数。如果抛出,则放弃担保,效果未指定。

注记

专业化STD::向量<bool>没有emplace_back()成员直到C++14。

下面的代码使用emplace_back添加类型对象President转到std::vector.它证明了emplace_back将参数转发到President构造函数,并演示如何使用emplace_back使用时,避免了所需的额外复制或移动操作。push_back...

二次

#include <vector> #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::vector<President> elections; std::cout << "emplace_back:\n"; elections.emplace_back("Nelson Mandela", "South Africa", 1994 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.

二次

另见

push_backadds an element to the end (public member function)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/容器/Vectoral/emplace[医]背