emplace與insert

c++中容器定義了很多操作。其中有6種操作:
emplace_front,emplace,emplace_back;
push_front,insert,push_back
都可以向容器中添加元素,但是其中又有很大的區別。下面有一程序:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

class Dog
{
public:
    string name;
    int age;
public:
    Dog(string n, int a) :name(n), age(a){ };
    Dog(string n) :name(n), age(0){ cout << "調用了構造函數" << endl; };
    Dog() = default;
};

int main()
{
    vector<Dog> q;
    q.push_back("2ha");
    for (auto a : q)
    {
        cout << a.name << ' ' << a.age << endl;
    }
    getchar();
}

爲了方便查看結果,我將所有成員都設置成了公共的。
VS2013編譯時會在q.push_back(“2ha”); 報錯
我將程序中的q.push_back(“2ha”);改成了q.emplace_back(“2ha”);
程序編譯通過。運行結果是
l
這說明emplace是調用構造函數,直接在容器中構造一個元素。
而insert,push是拷貝操作,將元素拷貝到容器中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章