初始化 class 中向量的向量的两个维度

Initializing both dimensions of a vector of vectors inside a class

我有一个class

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

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

This question asks about the same question for a vector of integers, and this 询问向量向量的初始化,但在任何 class 之外。我想初始化两个维度的大小,但向量是 class 成员。

我该怎么做?

你可以把它们放在成员初始值设定项列表中


像这样

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

是否要使用现有数据进行初始化?

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