What 结论
emplace_back(…)的效率比push_back(…)高。
Why
emplace_back(…)容器直接按照参数构造对象;push_back(…)则需要一次构造和一次移动构造(或者一次复制构造)。
How
#include <iostream>
#include <vector>
#include <list>
#include <queue>
using namespace std;
struct Student {
string name;
int age;
Student(string&& n, int a)
:name(std::move(n)), age(a)
{
cout << "构造" << endl;
}
Student(const Student& s)
: name(s.name), age(s.age)
{
cout << "拷贝构造" << endl;;
}
Student(Student&& s)
:name(std::move(s.name)), age(s.age)
{
cout << "移动构造" << endl;
}
};
int main()
{
vector<Student> classes_one;
vector<Student> classes_two;
cout << "emplace_back:" << endl;
classes_one.emplace_back("xiaohong", 24);
cout << "push_back:" << endl;
classes_two.push_back(Student("xiaoming", 23));
}
emplace_back:
构造
push_back:
构造
移动构造