std::deque::emplace_back
STD::deque::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)......
所有迭代器,包括过去的结束迭代器,都是无效的.。没有引用无效。
参数
args | - | arguments to forward to the constructor of the element |
---|
类型要求
-T%28容器%27s元素类型%29必须满足EmplaceConstrucable的要求。
返回值
(none) | (until C++17) |
---|---|
A reference to the inserted element. | (since C++17) |
复杂性
常量。
例外
如果引发异常,则此函数不具有%28强异常保证%29的效果。
例
下面的代码使用emplace_back
添加类型对象President
转到std::deque
.它证明了emplace_back
将参数转发到President
构造函数,并演示如何使用emplace_back
使用时,避免了所需的额外复制或移动操作。push_back
...
二次
#include <deque>
#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::deque<President> elections;
std::cout << "emplace_back:\n";
elections.emplace_back("Nelson Mandela", "South Africa", 1994
std::deque<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_back | adds an element to the end (public member function) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
http://en.cppreference.com/w/cpp/container/deque/emplace[医]背