c++ - 对象 vector - 如何向构造函数发送参数?

标签 c++ vector parameters constructor

假设我有以下代码:

struct obj{
    int v;
    obj(int i = 1){
        v = i;
    }
};

int main(){
    vector<obj> v1(10);    // (1)
    vector<obj> v2(15);    // (2)
}

根据以上内容:

Number (1) 创建一个包含 10 个 obj 实例的 vector 默认 v=1 .
数字 (2) 如何将 15 作为参数发送到 obj 所以 v=15 ???

我在网上搜索了这个 article 在这个网站上,但它似乎是关于更高级的东西,作为一个新手,我没有得到它。

最佳答案

vector<obj> v1(10);     // creates a vector of 10 obj, each initialized 
                        // with the default value 1

vector<obj> v2(10, 15); // creates a vector of 10 obj, each initialized 
                        // with the value 15

如果你想传递多个参数给构造函数:

vector<obj> v3(10, obj(15, x, y)); // creates a vector of 10 obj, each 
                                   // initialized with (15, x, y)

您当然必须提供一个构造函数,该构造函数需要三个参数才能正常工作。

关于c++ - 对象 vector - 如何向构造函数发送参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49826456/

相关文章:

c++ - 为什么 const QString& param 返回指向数据的错误 const char* 指针

c++ - 检测 typedef 的等价性

C++:在类 w.r.t. 的 vector 上选择 argmax任意表达

post - 如何使用参数重定向 Action 作为 Struts 中的帖子?

sql-server - 在不使用存储过程的情况下将 TEXT 参数添加到 ADODB.Command

c++ - 如何在 sublime text 2 界面中为 c++ 创建 header ?

python - 向量化最近邻计算

c++ - 非法访问内存中的 vector

java - 为什么我们可以使用 'this'作为实例方法参数?

c++ - 我如何最好地阅读 boost 序列化文件?