視頻教程:https://www.bilibili.com/video/av86157003
emplace_back的特點
- 當(dāng)調(diào)用push_back或insert成員函數(shù)時蹬碧,是把元素類型的對象傳遞給它們舱禽,這些對象被拷貝到容器中。而當(dāng)我們調(diào)用一個emplace系列函數(shù)時恩沽,則是將相應(yīng)參數(shù)傳遞給元素類型的構(gòu)造函數(shù)誊稚。
- 這樣emplace_back能就地通過參數(shù)構(gòu)造對象,不需要拷貝操作罗心,相比push_back能更好的避免內(nèi)存的拷貝和移動里伯,提升容器插入元素的性能。
- 大多數(shù)情況都應(yīng)該使用emplace系列函數(shù):emplace; emplace_back; emplace_hit; emplace_fornt; emplace_after
emplace系列函數(shù)需要有對應(yīng)的構(gòu)造函數(shù)
- emplace函數(shù)需要對應(yīng)的參數(shù)對象有對應(yīng)的構(gòu)造函數(shù)渤闷,不然編譯報錯
- emplace函數(shù)在容器中直接構(gòu)造元素疾瓮。傳遞給emplace函數(shù)的參數(shù)必須與元素類型的構(gòu)造函數(shù)相匹配
#include<iostream>
#include<list>
struct A
{
int x;
double y;
A()
{
x = 0;
y = 1.0;
}
A(int a, double b)
{
x = a;
b = y;
}
};
int main()
{
std::list<A> listSample;
listSample.emplace_back(1, 2.0);
std::cout << listSample.size() << std::endl;
return 0;
}
emplace_back和push_back的簡單比較
///////////////////////////////////////////////////////
// reference: http://en.cppreference.com/w/cpp/container/vector/emplace_back
namespace {
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 emplacevspush()
{
std::cout << "test_emplace_2()" << std::endl;
/*
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.
*/
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";
}
return 0;
}
//output
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函數(shù)可以減少一次拷貝或移動構(gòu)造的過程飒箭,提升容器插入數(shù)據(jù)的效率