首页 > 解决方案 > 如何使用 c++ 中的构造函数初始化 unique_ptrs 的 2d 向量?

问题描述

我正在尝试初始化 unique_ptrs 的 2d 向量以将其大小和每个索引设置为 nullptr,或者如果我想要一些基类对象指针但它不起作用。

#include <vector>
#include <memory>

class Base
{
}

int main()
{
    int m_width = 150, m_length = 13;

    vector <vector <std::unique_ptr<Base>>> m_board;

    m_board(m_length, vector < std::unique_ptr<Base>(m_width, nullptr));
}

也试过这个方法,还是没有:

m_board(m_length, vector < std::unique_ptr<Base>(std::move(m_width, nullptr)));

也是这样:

m_board(m_length, vector < std::unique_ptr<Base>(std::move(std::make_unique(m_width, nullptr))));

仍然没有任何工作,现在我使用一个非常丑陋的函数和两个 for 循环来做到这一点,但我确信有一种方法可以通过使用向量和 unique_ptr 的构造函数来完成这项工作。有什么想法吗?

标签: c++vectorvisual-studio-2019stdvectorunique-ptr

解决方案


首先,如果std::vector已经构建,vector则通过使用来更改 的大小std::vector::resize。您的代码将构造与已构造向量的大小混合在一起。

第二件事是双参数向量构造函数的第二个参数(参见 (4))现在是 C++ 14 或更高版本的分配器,而不是默认值。

因此,设置向量的最简单方法是首先resize将外部向量,然后resize每个内部向量单独循环:

#include <vector>
#include <memory>
#include <iostream>

class Base
{
};

int main()
{
    int m_width = 150, m_length = 13;

    // Create a vector with m_length size 
    std::vector<std::vector<std::unique_ptr<Base>>> m_board(m_length);

    // individually resize the inner dimensions
    for (auto& m : m_board)
       m.resize(m_width);
}

推荐阅读