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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值