【问题标题】:Initializing both dimensions of a vector of vectors inside a class初始化类内向量向量的两个维度
【发布时间】:2017-01-13 16:40:25
【问题描述】:

我有课

class A
{
    private:   
        std::vector< std::vector<int> > v;
    //other statements
}

我想通过将向量的两个维度传递给类的构造函数来初始化它们,可能使用初始化列表。

This 问题询问关于整数向量的相同问题,this 询问关于向量向量的初始化,但在任何类之外。我想初始化两个维度的大小,但是向量是类成员。

我该怎么做?

【问题讨论】:

  • 使用第二种方法,将它们放在member initializer lists(或者你可以在构造函数体中使用resize)
  • @appleapple 谢谢,但是如何使用它来初始化两个维度?
  • 就像第二个例子

标签: c++ class vector initialization stdvector


【解决方案1】:

您想使用现有数据进行初始化吗?

struct Matrix
{
    Matrix(std::initializer_list< std::initializer_list<int> > ilil)
    {
        data_.reserve(ilil.size());
        for (auto&& il : ilil)
        {
            data_.emplace_back(il);
        }
    }

    std::vector< std::vector<int> > data_;
};

void test()
{
    auto m = Matrix {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };
}

【讨论】:

    【解决方案2】:

    你可以把它们放在成员初始化列表中


    喜欢这个

    class A{
    public:
       A(int dim1,int dim2):v(dim1,std::vector<int>(dim2)){}
    private:   
       std::vector< std::vector<int> > v;
    };
    

    或者你可以使用vector::resize

    class A{
    public:
       A(int dim1,int dim2){v.resize(dim1,std::vector<int>(dim2));}
    private:   
       std::vector< std::vector<int> > v;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-26
      • 2011-05-18
      • 1970-01-01
      • 2011-03-04
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多