个人技术分享

push_back和emplace_back的区别

#include <iostream>
#include <vector>

using namespace std;
class testDemo {
public:
    testDemo(int n) :num(n) {
        cout << "构造函数" << endl;
    }
    testDemo(const testDemo& other) :num(other.num) {
        cout << "拷贝构造函数" << endl;
    }
    testDemo(testDemo&& other) :num(other.num) {
        cout << "移动拷贝构造函数" << endl;
    }
private:
    int num;
};

int main() {
    vector<testDemo> vec{};
    cout << "push_back:" << endl;
    vec.push_back(1);
    cout << endl;

    vector<testDemo> vec1{};
    cout << "第一个元素empalce_back:" << endl;
    vec1.emplace_back(1);
    cout << endl;

    cout << "不是第一个元素empalce_back:" << endl;
    vec1.emplace_back(2);

    return 0;
}

所以emplace_back()的高效好像只体现在第一个元素。

所以说empalce不拷贝,不完全正确。

list和vector的front和back

list既有push_back,push_front,也有emplace_back(),emplace_front().

vector只有psuh_back和emplace_back()。

insert和empalce

都是在指定的位置插入一个元素。

原理

#include <iostream>
#include <vector>
using namespace std;
class testDemo {
public:
    testDemo(int n) :num(n) {
        cout << "构造函数" << endl;
    }
    testDemo(const testDemo& other) :num(other.num) {
        cout << "拷贝构造函数" << endl;
    }
    testDemo(testDemo&& other) :num(other.num) {
        cout << "移动拷贝构造函数" << endl;
    }
    testDemo& operator=(const testDemo& other);
private:
    int num;
};
/*
为什么一定要重载这个函数:
1,自定义类型,这个函数不是默认生成的;
2,emplace和insert内部实现需要这个函数
*/
testDemo& testDemo::operator=(const testDemo& other) {
    this->num = other.num;
    cout << "重载" << endl;
    return *this;
}
int main() {
    vector<testDemo> vec{};
    cout << "第一个元素emplace:" << endl;
    vec.emplace(vec.begin(), 2);
    cout << endl;
    cout << "不是第一个元素emplace:" << endl;
    vec.emplace(vec.begin() + 1, 3);
    cout << endl;

    cout << "insert:" << endl;
    vec.insert(vec.begin(), 2);

    return 0;
}

总结:

emplace以及empalce_back除非第一个元素不拷贝,之后的元素加入和push和push_back差不多,都需要拷贝。