【问题标题】:initializing a vector of vectors of a user defined初始化用户定义的向量的向量
【发布时间】:2013-11-01 13:16:14
【问题描述】:

我有这个结构

struct myStruct {
    int a;
    int b;
    }

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

我正在尝试使用fill constructor 像这样:

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

这段代码在main 中运行良好,但是当我在一个类中有V 时,我如何在类构造函数中做到这一点。

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

产生错误的代码是:

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

【问题讨论】:

  • 使用初始化列表。

标签: c++ vector initialization


【解决方案1】:

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

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

现在你的主要问题:当你的向量在一个类中时,如果成员是非静态的,则使用初始化列表,或者如果它是静态的,则在声明部分初始化成员。

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);

【讨论】:

  • 如果我不能使用初始化列表?我的构造函数需要一个文件,读取数据然后需要初始化,我该怎么做?
  • @Mhd.Tahawi 如果你不能使用初始化列表,你可以在构造函数体内使用赋值:MyClass(int n) {V = vector&lt;vector&lt;edge&gt; &gt;(n); }
【解决方案2】:

只需省略tempV 所在的类的构造函数应如下所示:

MyClass(size_t n) : V(n) {}

【讨论】:

    【解决方案3】:
    class A
    {
    private:
        std::vector<std::vector<myStruct>> _v;
    public:
        A() : _v(10) {} // if you just want 10 empty vectors, you don't need to supply the 2nd parameter
        A(std::size_t n) : _v(n) {}
        // ...
    };
    

    您使用初始化列表进行这种初始化。

    【讨论】:

      猜你喜欢
      • 2020-04-12
      • 1970-01-01
      • 2011-03-04
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多