vector学习之insert和emplace操作

我们知道向vector容器里插入数据时使用insert函数,但是C++11又增加了一个emplace函数,它的功能与emplace_back原理一样,是构造一个对象添加到容器中,这样就省去了拷贝的副本,提高了性能,操作对比如下:

#include <iostream>
#include <vector>
#include <time.h>

using namespace std;

typedef struct Personal
{
    int m_age;
    int m_height;
    string m_name;

    Personal(int age, int height, std::string name)
        :m_age(age), m_height(height), m_name(name)
    {
        //cout << "constructed=======Personal===age=" << age << endl;
    }

    Personal(const Personal& other)
        :m_age(other.m_age)
        , m_height(other.m_height)
        , m_name(other.m_name)
    {
        //cout << "copy constructed====Personal==age=" << m_age << endl;
    }



    ~Personal()
    {
        //cout << "destructor~~~Personal=========age~" << m_age << endl;
    }

}Person;


void insert_emplace_reserve_Test()
{
    int count = 214748;//214748
    string name = string("床前明月光,疑似地上霜,举头望明月,低头思故乡。");
    double startTime1 = clock();//1计算开始
    vector<Person> vec1;
    cout << "insert_emplace_reserve_Test==========" <<endl;
    for(int i = 0; i < count; i++)//214748
    {
        Person person(i, i, name);
        vec1.insert(vec1.begin() + i, person);
    }
    double endTime1 = clock();//1时间结束
    cout << "vec1.size=" << vec1.size() << " vec1.capacity=" << vec1.capacity() << endl;
    vec1.clear();
    cout << "for    1 run time is: " << (double)(endTime1 - startTime1) / CLOCKS_PER_SEC << "s" << endl;
    cout << endl;

    double startTime2 = clock();//2计算开始
    for(int i = 0; i < count; i++)
    {
        Person person(i, i, name);
        vec1.emplace(vec1.begin() + i, person);
    }
    double endTime2 = clock();//2时间结束
    cout << "vec2.size=" << vec1.size() << " vec2.capacity=" << vec1.capacity() << endl;
    vec1.clear();
    cout << "for    2 run time is: " << (double)(endTime2 - startTime2) / CLOCKS_PER_SEC << "s" << endl;
    cout << endl;
    vector<Person> vec3;
    vec3.reserve(count);
    double startTime3 = clock();//3计算开始
    for(int i = 0; i < count; i++)
    {
        Person person(i, i, name);
        vec3.emplace(vec3.begin() + i, person);
    }
    double endTime3 = clock();//3时间结束
    cout << "vec3.size=" << vec3.size() << " vec3.capacity=" << vec3.capacity() << endl;
    vec3.clear();
    cout << "for    3 run time is: " << (double)(endTime3 - startTime3) / CLOCKS_PER_SEC << "s" << endl;
    cout << endl;
}


int main()
{
    //int = [-2147483648, 2147483647]

    insert_emplace_reserve_Test();
    cout << endl;

    cout << "Hello World!" << endl;
    return 0;
}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值