欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vector学习之insert和emplace操作

程序员文章站 2022-02-05 19:28:23
...

我们知道向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;
}

vector学习之insert和emplace操作

 

 

相关标签: STL vector stl