Life is short, use emplace_back()。探究一下C++11的push_back, move, rvalue, emplace_back

前言

一直以来写代码,vector想都没想就是push_back,今天发现的C++11的emplace_back碾压了传统的push_back

总结一句话:Life is short, use emplace_back()

简单叙述原因:emplace_back可以“同时构造和插入,一次搞定”,push_back需要“先构造,后插入,而且插入的时候还伴随着拷贝或者移动”。


Talk is cheap, show me the code

#include <iostream>
#include <utility>
#include <chrono>
#include <vector>
#include <string>
using namespace std;
using namespace chrono;


int main()
{
    vector<string> v;
    int num = 100000;
    v.reserve(num);                    // capacity 一次性增大到十万,减少vector多次增大时候的拷贝次数

    cout << "push_back way one:     ";
    auto start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        string temp("caitao");
        v.push_back(temp);             // push_back(const string&),参数是左值引用
    }
    auto end = system_clock::now();
    auto duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "push_back way two:     ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        string temp("caitao");
        v.push_back(move(temp));       // push_back(string &&), 参数是右值引用。
        // move可以理解为类型转换:左值引用 → 右值引用。右值引用就是临时对象。
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "push_back way three:   ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.push_back(string("caitao")); // push_back(string &&), 参数是右值引用
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "push_back way four:    ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.push_back("caitao");         // push_back(string &&),参数是右值引用,和 way three 几乎一样(只有vector元素是string才可以这么写,为了C++和C的字符串兼容)
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "emplace_back(fastest): ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.emplace_back("caitao");      // 只有一次构造函数,不调用拷贝构造函数,速度最快
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    system("pause");
    return 0;
}

分析

push_back emplace_back

第一种方法,速度最慢。push_back的参数是左值引用。首先定义一个temp对象的时候,调用一次构造函数,然后push_back的时候调用一次拷贝构造函数。两次构造很花时间,因为内存里面需要重新分配空间。

第二~四种方法,速度中等。push_back的参数是右值引用。首先定义一个temp对象的时候,调用一次构造函数,然后push_back的时候调用一次移动构造函数。移动构造函数花的时间比拷贝构造函数花的时间,因为不需要内存重新分配空间。(不知道为什么第二种方法会比方法三和四花费的时间多一点点。。。)

第五种方法,即emplace_back速度最快,因为emplace_back只调用一次构造函数,没有移动构造函数,也没有拷贝构造函数。cplusplus.com说:Arguments forwarded to construct the new element. 意思是:emplace_back的参数就是构造函数的参数。


证明上述的分析

写一个类,重载构造函数,重载拷贝构造函数,重载移动构造函数。代码如下:

#include <vector> 
#include <string>
#include <iostream>
using namespace std;

struct Complicated
{
    int year;
    double country;
    string name;

    Complicated(int a, double b, string c) :year(a), country(b), name(c)
    {
        cout << "is constucted" << endl;
    }

    Complicated(const Complicated & other) : year(other.year), country(other.country), name(other.name)
    {
        cout << "is copied" << endl;
    }

    Complicated(Complicated && other) : year(move(other.year)), country(move(other.country)), name(move(other.name))
    {
        cout << "is moved" << endl;
    }
};

int main()
{
    int anInt = 4;
    double aDouble = 5.0;
    string aString = "C++";

    vector<Complicated> v;
    v.reserve(10);

    cout << "--emplace_back--" << endl;
    v.emplace_back(anInt, aDouble, aString);            // construct

    cout << endl << "--push_back--" << endl;
    Complicated temp(anInt, aDouble, aString);          // construct
    cout << endl;

    v.push_back(temp);                                  // copy
    cout << endl;

    v.push_back(move(temp));                            // move
    cout << endl;

    v.push_back(Complicated(anInt, aDouble, aString));  // construct + move
    cout << endl;

    system("pause");
    return 0;
}

输出结果如下:
move_copy



一种“更加公平”的比较方式

emplace_back可以“构造和插入同时进行”,堪称“开挂”。如果对象构造好了,只是单纯的比较插入(抛开外挂),谁快一些呢?

这次是“单纯”比较的push_back和emplace_back的插入功能:

#include <iostream>
#include <utility>
#include <chrono>
#include <vector>
#include <string>
using namespace std;
using namespace chrono;

int main()
{
    vector<string> v;
    int num = 100000;
    v.reserve(num);                    // capacity 一次性增大到十万,减少vector多次增大时候的拷贝次数

    string caitao("caitao");
    vector<string> storage(num, caitao);

    cout << "push_back(copy):  ";
    auto start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.push_back(storage[i]);
    }
    auto end = system_clock::now();
    auto duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "push_back:(move): ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.push_back(move(storage[i]));
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    cout << "emplace_back:     ";
    v.clear();
    start = system_clock::now();
    for (int i = 0; i < num; ++i)
    {
        v.emplace_back(storage[i]);
    }
    end = system_clock::now();
    duration = duration_cast<microseconds>(end - start);
    cout << duration.count() << " microseconds." << endl << endl;

    system("pause");
    return 0;
}

emplace_back

emplace_back最快,push_back(move())次之,push_back最慢。所以呀,大家忘了push_back吧(除非特殊情况,比如?)


last update: 2017/5/10

这段代码实现了一个并查集数据结构。并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。它支持两种操作: - 查找(Find):确定元素属于哪一个子集。它可以被用来确定两个元素是否属于同一子集。 - 合并(Union):将两个子集合并成同一个集合。 并查集可以用于解决很多实际问题,例如: - 判断无向图中是否有环 - 在图像处理中,判断连通区域 - 在游戏开发中,判断游戏中角色的关系 在这段代码中,类 UnionFindSet 的初始化函数 __init__ 接收两个参数:起始点 start 和结束点 n。接着定义了两个列表 pre 和 rank,用于存储每个节点的父节点和树的深度。其中,pre[i] 表示节点 i 的父节点,如果 pre[i] = i,则 i 为该集合的代表元素。 接下来的函数 init 用于初始化并查集,将每个节点的父节点设置为自身,深度为 1。 函数 find_pre 用于查找节点 x 的代表元素,同时实现了路径压缩的优化,即将查找路径上的所有节点都直接连接到代表元素上,减少查找时间。 函数 is_same 用于判断节点 x 和节点 y 是否在同一个集合中,即是否具有相同的代表元素。 函数 unite 用于合并两个集合,即将 x 所在的集合和 y 所在的集合合并为一个集合。首先查找 x 和 y 的代表元素,如果它们已经在同一个集合中,则直接返回 False。否则,将深度较小的集合连接到深度较大的集合上,并更新代表元素和深度。 最后,函数 is_one 用于判断整个并查集是否只有一个集合。它首先找到起始点的代表元素 temp,然后遍历起始点到结束点之间的所有节点,如果存在任意一个节点的代表元素不等于 temp,则说明存在多个集合,返回 False;否则,所有节点都在同一个集合中,返回 True。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值