stl 向量和 C++:如何在没有默认构造函数的情况下调整大小?
我如何告诉 STL,特别是向量中的 resize()
方法,用一个非默认的构造函数初始化对象,以及使用哪些参数?
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?
例如:
class something {
int a;
something (int value);
}
std::vector<something> many_things;
many_things.resize (20);
更一般地说,当 STL 需要创建对象并将参数传递给该构造函数时,我如何强制它使用我的构造函数?
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.
推荐答案
使用 2 参数重载:many_things.resize(20, something(5));
相关文章