c++ - 如何在构造函数调用中使用初始化列表来配置 `std::vector<std::vector<MyClass>>`?

标签 c++ class c++11 stdvector stdinitializerlist

大约一个小时前,我被指出了一个叫做初始化列表的东西,所以我立即开始研究它,但有一件事我不明白。

如果我有类似的东西:

class ExtClass {
    public:
        int ext;
        int pet;        
        ExtClass();
};

ExtClass::ExtClass() {
    this->ext = rand();
    this->pet = rand();
}

class MainClass {
    public:    
        std::vector<std::vector<ExtClass>> attribute;

        MainClass(std::vector<int>>);
};

MainClass::MainClass(std::vector<int> varName) : attribute(...) { }

问题是我希望这发生:

attribute[0] has {1, 2, 3, 4} of type ExtClass
attribute[1] has {5, 6}       of type ExtClass
attribute[2] has {7, 8, 9}    of type ExtClass

等等。

我想要的是当我打电话时:

std::vector<int> a{4, 2, 3};
MainClass mainObject(a);

获取我写的例子:

attribute[0] reserves 4 places and creates 4 objects using ExtClass constructor
attribute[1] reserves 2 places and creates 2 objects using ExtClass constructor
attribute[2] reserves 3 places and creates 3 objects using ExtClass constructor

是否有任何简短的方法可以使用初始化列表来做到这一点,或者我是否需要采取另一种方法(如果需要的话)?

最佳答案

您可以 std::vector::resize std::vector<ExtClass> 的每个 vector MainClass 的构造器中.

查看 ( sample code )

MainClass(const std::vector<int>& vec)
    : attribute(vec.size())
{
    int row = 0;
    // each cols will be resized to as per
    for(const int colSize: vec) attribute[row++].resize(colSize);
}

或作为 @RSahu 在评论中建议。

MainClass(const std::vector<int>& vec)
{
    attribute.reserve(vec.size()); // reserve the memory for row = vec.size()
    for (const int colSize : vec)
        attribute.emplace_back(std::vector<ExtClass>(colSize));
}

关于c++ - 如何在构造函数调用中使用初始化列表来配置 `std::vector<std::vector<MyClass>>`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56263581/

相关文章:

python - 如何确定实例方法对应的类?

c++ - POSIX 扩展正则表达式 - 不包含 X 但包含 Y (std::regex c++11)

c++ - 非 POD 类类型的聚合初始化?

c++ - 多次使用 QNetworkAccessManager GET

c++ - 如何在 Eclipse 中使用 MinGW 编译 boost 线程?

c++ - 在函数调用中,为什么 nullptr 不匹配指向模板对象的指针?

c++ - 为什么 std::is_function<T> 会导致编译错误?

c++ - Boost Polygon 的用途是什么?

ios - 将类应用于对象 iOS

python - 如何在没有无限递归错误的情况下实现 __getattribute__?