vector学习之emplace_back() 和 push_back()操作

开发环境 Window10 Qt5.13.1

最近在编译Chromium的源码,修改启动参数时,在command_line文件中,参数的添加,有的是push_back操作,有的是emplace_back操作,因此学习下这两者的区别这两个操作都是在容器的尾部添加一个无素,push_back操作时先创建一个新的元素,然后再将该元素的拷贝添加到容器中,而emplace_back的操作是直接将构造的元素添加到容器中,省略了拷贝这个操作,(Primer C++ 9.3.1节)。下面看下这个示例:

#include <iostream>
#include <vector>
#include <string>
#include <ctime>

class PersonInfo
{
public:
    PersonInfo(std::string name, int age)
        :m_strName(name), m_nAge(age)
    {
        std::cout << "call constructed=============" << std::endl;
    }

    PersonInfo(const PersonInfo &other)
        :m_strName(other.m_strName), m_nAge(other.m_nAge)
    {
        std::cout << "call copy constructed==========" << std::endl;
    }

    PersonInfo(PersonInfo &&other)
        :m_strName(other.m_strName), m_nAge(other.m_nAge)
    {
        std::cout << "call move constructed==========" << std::endl;
    }

    PersonInfo& operator=(const PersonInfo& other);

//private: //不能用私有,不然main函数里不能打印
    std::string m_strName;
    int m_nAge;
};



int main()
{
    //基于当前系统的当前日期、时间
    time_t start = time(nullptr);//__int64
    std::cout << "current time:" << start << std::endl;
    std::vector<PersonInfo> vecMan;
    std::cout << "emplace_back:" << std::endl;
    vecMan.emplace_back("Scott", 3);//没有类的创建

    std::vector<PersonInfo> vecWoman;
    std::cout << "push_back:" << std::endl;
    vecWoman.push_back(PersonInfo("Camel", 3));

    std::cout << "\nContents:\n";

    for(PersonInfo const &man: vecMan)
    {
        std::cout << "man name = " << man.m_strName << "  age = " << man.m_nAge << std::endl;
    }

    std::cout << std::endl;
    for(PersonInfo const &woman: vecWoman)
    {
        std::cout << "woman name = " << woman.m_strName << "  age = " << woman.m_nAge << std::endl;
    }

    time_t end = time(nullptr);//__int64

    std::cout << "Hello World!===========run time ====" << (end - start) << std::endl;
    return 0;
}

运行结果:

参考:

https://blog.csdn.net/xiaolewennofollow/article/details/52559364
https://blog.csdn.net/netyeaxi/article/details/83242362
https://blog.csdn.net/u012088909/article/details/105309570


版权声明:本文为chenyijun原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。