初始化用户定义的向量的向量 [英] initializing a vector of vectors of a user defined

查看:62
本文介绍了初始化用户定义的向量的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个结构

struct myStruct {
    int a;
    int b;
    }

我想创建一个vector <vector<myStruct> > V并将其初始化为vector<myStruct>类型的n空向量

I want to create a vector <vector<myStruct> > V and initialize it to n empty vectors of type vector<myStruct>

我正在尝试使用填充构造函数 像这样:

I'm trying to use the the fill constructor like this:

vector<edge> temp;
vector<vector<edge> > V(n, temp);

此代码在main中工作正常,但是当我在类中包含V时,如何在类构造函数中执行此操作.

This code works fine in main, but when I have V inside a class how can I do that inside the class constructor.

当我在类构造函数中执行此操作时,出现以下错误:
no match for call to '(std::vector<std::vector<edge> >) (int&, std::vector<edge>&)'

when I do it in my class constructor I get the following error:
no match for call to '(std::vector<std::vector<edge> >) (int&, std::vector<edge>&)'

产生错误的代码是:

the code generating the error is:

vector<myStruct> temp;
V(n,  temp); // n is a parameter for the constructor

推荐答案

首先,请注意,不需要temp:您的代码与

First, note that temp is not necessary: your code is identical to

vector<vector<edge> > V(n);

现在要回答的主要问题是:当向量在类中时,如果成员是非静态的,则使用初始化列表,如果成员是静态的,则在声明部分中初始化该成员.

Now to your main question: When your vector is inside a class, use initializer list if the member is non-static, or initialize the member in the declaration part if it is static.

class MyClass {
    vector<vector<edge> > V;
public:
    MyClass(int n) : V(n) {}
};

或类似这样:

// In the header
class MyClass {
    static vector<vector<edge> > V;
    ...
};

// In a cpp file; n must be defined for this to work
vector<vector<edge> > MyClass::V(n);

这篇关于初始化用户定义的向量的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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