在C++里,emplace_back可以完全取代push_back吗?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在C++里,emplace_back可以完全取代push_back吗?相关的知识,希望对你有一定的参考价值。

另外能否把emplace_back和push_back的区别详细的说一下?

emplace_back和push_back都是向容器内添加数据.

对于在容器中添加类的对象时, 相比于push_back,emplace_back可以避免额外类的复制和移动操作.

"emplace_back avoids the extra copy or move operation required when using push_back."

参见: http://en.cppreference.com/w/cpp/container/vector/emplace_back

注意下面代码中的emplace_back和push_back的添加方式(VS2012下编译通过):

#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);
;

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能否完全代替push_back?

追答

是不能完全代替的吧。
原话"emplace_back avoids the extra copy or move operation required when using push_back."

参考技术A push_back的参数对象必须是已经存在的对象,emplace_back不是 参考技术B This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.
只有当你增加的对象使得vector的size>capacity时,会触发vector重新分配内存,增大capacity.
如果这个时候你传入的是迭代器对象,由于vector重新分配内存时,迭代器失效,这时这个操作会有错误,你会传个无效迭代器进去

以上是关于在C++里,emplace_back可以完全取代push_back吗?的主要内容,如果未能解决你的问题,请参考以下文章

C++的emplace_back函数介绍

C++ emplace emplace_back是什么

c++顺序容器

C++中出现错误has no member named 'emplace_back怎么办?

自动化篇 | 这些自动化场景,批处理脚本完全可以取代 Python!

(C++)用upper_bound函数取代自己写的二分查找