std::vector::emplace_back
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
template< class... Args > void emplace_back( Args&&... args ); |
(C++11 起) | |
添加一个新元素到结束的容器。该元件是构成在就地,即没有复制或移动操作进行。提供的功能完全一样的参数的构造函数的元素被称为.
原文:
Appends a new element to the end of the container. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments that are supplied to the function.
If the new size()
is greater than capacity()
, all iterators and references are invalidated. Otherwise no iterators and references are invalidated.
目录 |
[编辑] 参数
args | - | 元素的构造函数的参数转发
原文: arguments to forward to the constructor of the element |
[编辑] 返回值
(无)
[编辑] 复杂性
恒定
[编辑] 为例
下面的代码使用
emplace_back
追加到President
std::vector类型的对象。它演示了如何emplace_back
转发的President
构造函数的参数,并显示如何使用emplace_back
避免了额外的拷贝或移动操作时,需要使用push_back
.
原文:
The following code uses
emplace_back
to append an object of type President
to a std::vector. It demonstrates how emplace_back
forwards parameters to the President
constructor and shows how using emplace_back
avoids the extra copy or move operation required when using 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.
[编辑] 另请参阅
将元素添加到末端 (公共成员函数) |