我是靠谱客的博主 懵懂黑米,这篇文章主要介绍C++:Vector中push_back和emplace_back到底有什么区别?,现在分享给大家,希望可以做个参考。

push_back应该是我们最常使用的标准容器,而且对于LZ这种C++菜鸟,主要C++写的风格其实还是C,所以,理解不到位处还请小伙伴批评指正。

这是在阅读其他代码的时候发现了一个emplace_back的用法,但是LZ之前没遇到过,所以就很想知道emplace_back和push_back之间到底有什么区别呢?

先看下官方文件,emplace_back是从C++11开始的一个新特性,一直到后续的C++17,主要是将新元素添加到容器的末尾,元素呢是通过std :: allocator_traits :: construct构造的,通常使用placement-new在容器提供的位置就地构造元素。

以下是官网给出的一段示例代码:使用emplace_back将President类型的对象添加到std :: vector。它演示了emplace_back如何将参数转发到President构造函数,并演示了使用emplace_back如何避免使用push_back时所需的额外复制或移动操作

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#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"; } }

output:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.

从上面的例子中可以看到,使用emplace_back是不需要另外的copy或者移除操作的,而使用push_back则会存在额外的开销,但是在实际工程中也会存在一些问题,实际上并不是所有编译器都会支持c++11的,所以这个也要作为考虑的一个因素。

参考地址:
https://en.cppreference.com/w/cpp/container/vector/emplace_back

最后

以上就是懵懂黑米最近收集整理的关于C++:Vector中push_back和emplace_back到底有什么区别?的全部内容,更多相关C++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(73)

评论列表共有 0 条评论

立即
投稿
返回
顶部