SLAM

C++11_emplace_back的优点

2020-02-03  本文已影响0人  JasonLiThirty

视频教程:https://www.bilibili.com/video/av86157003

emplace_back的特点

emplace系列函数需要有对应的构造函数

#include<iostream>
#include<list>


struct A
{
    int x;
    double y;

    A()
    {
        x = 0;
        y = 1.0;
    }

    A(int a, double b)
    {
        x = a;
        b = y;
    }
};

int main()
{
    std::list<A> listSample;
    listSample.emplace_back(1, 2.0);
    std::cout << listSample.size() << std::endl;
    return 0;
}

emplace_back和push_back的简单比较

///////////////////////////////////////////////////////
// reference: http://en.cppreference.com/w/cpp/container/vector/emplace_back
namespace {
    struct President {
        std::string name;
        std::string country;
        int year;


        President(std::string p_name, std::string p_country, int p_year)
            : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
        {
            std::cout << "I am being constructed.\n";
        }
        President(President&& other)
            : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
        {
            std::cout << "I am being moved.\n";
        }
        President& operator=(const President& other) = default;
    };
}


int emplacevspush()
{
    std::cout << "test_emplace_2()" << std::endl;
    /*
    The following code uses emplace_back to append an object of type President to a std::vector.
    It demonstrates how emplace_back forwards parameters to the President constructor and shows
    how using emplace_back avoids the extra copy or move operation required when using push_back.
    */
    std::vector<President> elections;
    std::cout << "emplace_back:\n";
    elections.emplace_back("Nelson Mandela", "South Africa", 1994);


    std::vector<President> reElections;
    std::cout << "\npush_back:\n";
    reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));


    std::cout << "\nContents:\n";
    for (President const& president : elections) {
        std::cout << president.name << " was elected president of "
            << president.country << " in " << president.year << ".\n";
    }
    for (President const& president : reElections) {
        std::cout << president.name << " was re-elected president of "
            << president.country << " in " << president.year << ".\n";
    }


    return 0;
}

//output
emplace_back:
I am being constructed.


push_back:
I am being constructed.
I am being moved.


Contents:
Nelson Mandela was elected president of South Africa in 1994.
Franklin Delano Roosevelt was re-elected president of the USA in 1936.

如例子所示,使用emplace_back函数可以减少一次拷贝或移动构造的过程,提升容器插入数据的效率

上一篇下一篇

猜你喜欢

热点阅读