std::vector


文档

emplace 和 emplace_back

两者的区别仅为前者可以指定插入元素的位置,后者是直接插入到容器末尾

当调用push_backinsert成员函数时,是把元素类型的对象传递给它们,这些对象被拷贝到容器中(即需要调用一次拷贝构造函数)
但调用一个emplace系列函数时,则是将相应参数传递给元素类型的构造函数,直接构造出对象并插入到容器中,不需要调用拷贝构造函数
演示程序如下

#include 
#include 

using namespace std;

class A {
    public:
    int x;

    A() {
        x = 0;
        cout << "默认构造执行" << endl;
    }
    A(int x) {
        this->x = x;
        cout << "带参构造执行" << endl;
    }
    A(const A &a) {
        this->x = a.x;
        cout << "拷贝构造执行" << endl;
    }
};

int main() {
    vector vec;

    A a = A(1);
    vec.push_back(a);

    for (A &i : vec) cout << i.x << ' ';

    return 0;
}

执行结果:

#include 
#include 

using namespace std;

class A {
    public:
    int x;

    A() {
        x = 0;
        cout << "默认构造执行" << endl;
    }
    A(int x) {
        this->x = x;
        cout << "带参构造执行" << endl;
    }
    A(const A &a) {
        this->x = a.x;
        cout << "拷贝构造执行" << endl;
    }
};

int main() {
    vector vec;

    vec.emplace_back(2);

    for (A &i : vec) cout << i.x << ' ';

    return 0;
}

执行结果

emplace系列函数的核心在于调用插入元素的构造函数,因此传入的值要符合构造函数的要求