stl向量和c++:如何在没有默认构造函数的情况下调整大小?
我如何告诉 STL(特别是向量中的方法 resize()
)使用默认构造函数以外的构造函数以及使用哪些参数来初始化对象?
例如:
class something {
int a;
something (int value);
}
std::vector<something> many_things;
many_things.resize (20);
更一般地说,当 STL 需要创建对象并将参数传递给该构造函数时,如何强制 STL 使用我的构造函数?
就我而言,添加默认构造函数不是一个选项,而且我不想使用指针数组来解决问题。
How do I tell STL, specifically for the method resize()
in vector, to initialize objects with a constructor other than default, and with which parameters?
For example:
class something {
int a;
something (int value);
}
std::vector<something> many_things;
many_things.resize (20);
More generally, how do I force STL to use my constructor when it needs to create objects, and pass parameters to that constructor?
In my case adding a default constructor is not an option, and I'd prefer not to use an array of pointers to solve the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 2 参数重载:
many_things.resize(20, Something(5));
Use the 2-argument overload:
many_things.resize(20, something(5));
我可以想到一个解决方案,但我警告你,它相当难看。我不知道为什么你不想添加默认构造函数,但如果你只是想防止类的用户创建未初始化的实例,你可以将默认构造函数设为私有并将适当的向量类声明为友元:
这其丑陋有几个原因,主要是因为它仅适用于一种容器类型。没有其他方法,因为 STL 容器只要求它们的项是默认可构造的。
I can think of a solution, but iwarn you, it's rather ugly. I don't know why you do not want to add a default constructor, but if you just want to prevent users of the class to create unintialized instances, you can just make the default constructor private and declare the appropriate vector class a friend :
This is ugly for several reasons, mostly because it only works for one container type. There is no other way, because STL containers simply require their items to be default constructible.
您可以使用
reserve()
来增加缓冲区大小,并在循环中手动添加 (push_back()
) 必要的项目。You could use
reserve()
to increase the buffer size and manually add (push_back()
) the necessary items in a loop.具有类似的专业化(抱歉,我只进行了最少的检查就写了这篇文章)?
但想想你是否真的需要它。为什么不创建默认构造函数呢?
With specialization alike this (sorry, I wrote this with only minimal checks)?
But think if you really need it. Why not to create default constructor instead?