提问者:小点点

如何使用类的智能指针创建指针矩阵?


假设我们有以下c-style代码

class Dog {
public:
    void woof() {};
};

int main() {
    Dog* mat[5][5];

    mat[0][0] = new Dog();
    
    mat[0][0]->woof();
}

您将如何使用智能指针以cpp风格编写它?是不是下面就可以了?

class Dog {
public:
    void woof() {};
};

int main() {
    std::unique_ptr<Dog> mat[5][5];

    mat[0][0] = std::make_unique<Dog>();
    
    mat[0][0]->woof();

}

或者甚至可能是这样的东西:

class Dog {
public:
    void woof() {};
};

int main() {
    std::unique_ptr<std::unique_ptr<std::unique_ptr<Dog>[]>[]> mat = std::make_unique<std::unique_ptr<std::unique_ptr<Dog>[]>[]>(5);
    for (int i = 0; i < 5; i++)
        mat[i] = std::make_unique<std::unique_ptr<Dog>[]>(5);

    mat[0][0] = std::make_unique<Dog>();
    
    mat[0][0]->woof();

}

我怎样才能用最优雅,最高效的方式来做呢?


共1个答案

匿名用户

如果维度是固定的(我认为它们是固定的),那么您可以使用。然后循环并用填充元素:

#include <iostream>
#include <array>
#include <algorithm>
#include <memory>

class Dog {
public:
    void woof() { std::cout << "woof" << std::endl; };
};


int main() {
    std::array<std::array<std::unique_ptr<Dog>, 5>, 5> matrix;

    for (int x=0; x < 5; ++x)
    {
        std::generate(std::begin(matrix[x]), std::end(matrix[x]), 
            []{ return std::make_unique<Dog>(); } );
    }

    matrix[0][0]->woof();
    matrix[4][4]->woof();
    
    return 0;
}

演示