如何使用唯一对象调整std :: vector的大小(How to resize std::vector with unique objects)

系统教程 行业动态 更新时间:2024-06-14 16:57:18
如何使用唯一对象调整std :: vector的大小(How to resize std::vector with unique objects)

我有一个对象矢量。 每个对象都有一个boost::shared_ptr到一个不可复制的对象(一个boost::signal )。 对象的默认构造函数创建boost :: signal对象。

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

要将我的向量设置为包含X个别对象,我这样做了: -

vec.resize(X);

这没有达到我的预期,因为它使用默认构造函数来创建一个对象,然后使用复制构造函数来创建重复项。 我最终得到X对象,但它们都指向相同的boost::signal0对象。

有没有比在for循环中使用push_back更简单的方法来构建我的向量?

I have a vector of objects. Each object has a boost::shared_ptr to a noncopyable object (a boost::signal). the object's default constructor creates the boost::signal object.

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:-

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.

Is there an easier way of building my vector correctly than just using push_back in a for loop?

最满意答案

我能想到的唯一方法是使用reserve来使向量分配你需要的内存(如@Jonathan的回答)。 你可以使用带有std::back_inserter generate_n来添加元素:

FuncRef makeFuncRef() { return FuncRef(); } vec.reserve(vec.size() + n); std::generate(std::back_inserter(vec), n, makeFuncRef);

这种方法不需要reserve ,但如果n很大则可能更快。

The only way I can think of is to use reserve to make the vector allocate the memory you need (as @Jonathan answered). You can the use generate_n with an std::back_inserter to add the elements:

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.

更多推荐

本文发布于:2023-04-12 20:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/5ef90449587a8e3378776d065781652c.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   大小   对象   std   vector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!