stl 向量和 C++:如何在没有默认构造函数的情况下调整大小? [英] stl vector and c++: how to .resize without a default constructor?

查看:16
本文介绍了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));

这篇关于stl 向量和 C++:如何在没有默认构造函数的情况下调整大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆