C++ 11对容器的push_back, push_front, insert 增加了新的用法,与之对应的是emplace_back,emplace_front, emplace. 它们的作用是在操作容器时可以调用对应类型的构造数,例如下面的代码:
直接看例子:
#include <iostream>
#include <vector>
using namespace std;
struct Date
{
int _year;
int _month;
int _day;
Date(int year, int month, int day) :_year(year), _month(month), _day(day) {}
};
int main()
{
vector<Date> vecDate;
Date d1{ 2021, 6, 19 };
Date d2{ 2021, 6, 15 };
vecDate.push_back(d1);
vecDate.push_back(d2);
vecDate.push_back(Date(2021, 5, 30));
//vecDate.push_back(2021, 5, 30);
vecDate.emplace_back(2021, 5, 31);//push_back对比
for (auto d : vecDate)
{
cout << d._year << " " << d._month << " " << d._day << endl;
}
return 0;
}
输出结果
2021 6 19
2021 6 15
2021 5 30
2021 5 31