添加到C ++中的集合之前或之后 [英] Before or after when adding to sets in C++

查看:215
本文介绍了添加到C ++中的集合之前或之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定

my_type m;
std::vector<my_type> v;

哪种运行速度更快?

m.generate_data_inside_self();
v.push_back(m);

v.push_back(m);
v[0].generate_data_inside_self();

如果向量包含指向my_types的指针,那么两者看起来都是一样的。

If the vector held pointers to the my_types then both would seem about the same.

但是当在这个例子中复制整个my_type对象时,我认为第二个会更快,因为有更少的副本,因为额外的数据只有在m v。

However when copying in the whole my_type object as in this example I think the 2nd would be faster as there is less to copy as the extra data only comes into existance after "m" is inside "v".

编辑:

在我的程序中的示例my_type看起来像这样。 p>

In the example in my program my_type looks sort of like this.

my_type
{
    private:
        std::vector<unsigned short> data; //empty after construction

    public:
        //no destructors, assignment operators
        //copy constructors etc... explicitly (are) defined
        generate_data_inside_self() //populates data
        {
            //contains for example a loop that populates
            //"data" with some (lets say 50) values
        }
}


推荐答案

添加复制构造函数/较小。如果你正在生成数据,很可能会增加复杂性,在生成之前插入。

Add it when the complexity of copy constructor/operator == is smaller. If you are generating data, most likely increasing that complexity, insert before generating.

如果你有很多矢量拷贝,并且关注性能,我的建议是有一个向量的指针和 new (当然还有一天 delete )对象,并将它们放在向量中。这样,插入向量的成本不取决于对象的复杂性。

If you have many vector copies and you are concerned about performance, my suggestion is to have a vector of pointers and new (and of course one day delete) the objects and put them in the vector. That way, the cost of inserting in vector is not dependent on the complexity of the object.

这篇关于添加到C ++中的集合之前或之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆