[英]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.