简体   繁体   English

如何使用唯一对象调整std :: vector的大小

[英]How to resize std::vector with unique objects

I have a vector of objects. 我有一个对象矢量。 Each object has a boost::shared_ptr to a noncopyable object (a boost::signal ). 每个对象都有一个boost::shared_ptr到一个不可复制的对象(一个boost::signal )。 the object's default constructor creates the boost::signal object. 对象的默认构造函数创建boost :: signal对象。

struct FuncRef
{
    typedef boost::signal0<void, > Func;
    boost::shared_ptr <Func> function;
    FuncRef():
        function(new Func)
    {
    }
};

To set my vector to contain X individual objects, I did this:- 要将我的矢量设置为包含X个别对象,我这样做了: -

vec.resize(X);

This didn't do what I expected, because it uses the default constructor to make one object, and then the copy constructor to make the duplicates. 这没有达到我的预期,因为它使用默认构造函数来创建一个对象,然后使用复制构造函数来创建重复项。 I end up with X objects, but they all point to the same boost::signal0 object. 我最终得到X对象,但它们都指向相同的boost::signal0对象。

Is there an easier way of building my vector correctly than just using push_back in a for loop? 有没有比在for循环中使用push_back更简单的方法来构建我的向量?

The only way I can think of is to use reserve to make the vector allocate the memory you need (as @Jonathan answered). 我能想到的唯一方法是使用reserve来使向量分配你需要的内存(如@Jonathan的回答)。 You can the use generate_n with an std::back_inserter to add the elements: 你可以使用带有std::back_inserter generate_n来添加元素:

FuncRef makeFuncRef() {
    return FuncRef();
}

vec.reserve(vec.size() + n);
std::generate(std::back_inserter(vec), n, makeFuncRef);

The reserve is not necessary with this approach, although it is probably faster if n is large. 这种方法不需要reserve ,但如果n很大则可能更快。

The simplest way I can think of is to reserve the memory beforehand so that only one allocation is needed by the vector : 我能想到的最简单的方法是预先保留内存,以便vector只需要一次分配:

vec.reserve(X);

Then loop and push_back() . 然后循环和push_back() Is that not sufficient for your needs? 这不足以满足您的需求吗?

Are you not able to implement a copy constructor/copy assignment with actual copy semantics? 您是否无法使用实际的复制语义实现复制构造函数/复制赋值? Unless you're having serious performance with the vector filling this seems like the most obvious solution. 除非你在矢量填充方面有很好的表现,否则这似乎是最明显的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM