具有可变长度定义向量的初始化列表

Initializer list with a variable length defined vector

#include <vector>


using namespace std;

class NumArray 
{
    public:
        NumArray(vector<int>& nums)
            : nums(nums)
            , length(nums.size())
        {
            vector< vector<int> > tmp(length, vector<int> (length, NULL));
            this->lookup = tmp;
        }

    private:
        vector<int>& nums;
        vector< vector<int> > lookup;
        int length;
};

我通过先构造向量 tmp 得到了一个初始化向量 lookup 的低效方法,但是应该有一个方法初始化 lookup 显式地通过初始化列表。喜欢

public:
    NumArray(vector<int>& nums)
        : nums(nums)
        , length(nums.size())
        , lookup(length, vector<int> (length, NULL))
    {

    }

但这行不通。有什么办法可以解决吗?

你所做的工作正常,you're just not doing it right(强调我的):

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

  1. If the constructor is for the most-derived class, virtual bases are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)
  2. Then, direct bases are initialized in left-to-right order as they appear in this class's base-specifier list
  3. Then, non-static data member are initialized in order of declaration in the class definition.
  4. Finally, the body of the constructor is executed

这意味着在您的情况下:

private:
    vector<int>& nums;
    vector< vector<int> > lookup;
    int length;

lookuplength 之前初始化,因此,length 可能不会出现在 lookup 构造函数中。

交换两者的声明以解决问题,或者为了更可靠的解决方案,根本不要在成员初始值设定项列表中使用成员。这同样有效,不会导致您现在遇到的情况。

NumArray(vector<int>& nums)
        : nums(nums)
        , length(nums.size())
        , lookup(nums.size(), vector<int> (nums.size(), NULL)) {} // `length` does not need to be used at all