c++ 2d unique_ptr对象数组

c++ 2d array of unique_ptr objects?

本文关键字:对象 数组 ptr 2d unique c++      更新时间:2023-10-16

我正在尝试创建一个简单的2D数组或SFML的Sprite对象向量。我尝试了许多不同的方法,最终总是得到错误或只是一个空向量。

我试过了

// first x
for ( int c = 0; c < w ; ++c)
{
    vector<unique_ptr<sf::Sprite>> col;
    map.push_back(std::move(col));
    // then y
    for ( int r = 0; r < h ; ++r) {
        map[c].push_back(unique_ptr<sf::Sprite>(new sf::Sprite()));
    }
}

unique_ptr<sf::Sprite[0][0]> map;
...
map.reset(unique_ptr<sf::Sprite[0][0]>(new sf::Sprite[w][h]));

总的来说,我只是没有成功地制作一个2d智能指针对象数组,想知道是否有人可以帮助。对不起,如果我没有包括足够的细节,这是我的第一个帖子堆栈溢出,所以请温柔:)

编辑:让我给出更多的细节,对不起。我在工厂类型类中创建这个2d数组它基本上是单例的。所以我需要这个2d数组在它被创建并离开堆栈后继续存在,等等

您正在将map声明为指向多维数组的指针,并尝试将类型为std::vector<>的对象插入其中。相反,您可以使用向量(在本例中是向量的向量),并消除数组的分配,并在此过程中简化它。

#include <memory>
#include <vector>
namespace sf { class Sprite {}; }
int main()
{
    const int w = 5;
    const int h = 5;
    // vector of vectors of Sprites is what you're looking for
    std::vector<std::vector<std::unique_ptr<sf::Sprite>>>   map;
    // first x
    for ( int c = 0; c < w ; ++c)
    {
        // No need to access via index of c. Just append to the column vector itself.
        std::vector<std::unique_ptr<sf::Sprite>> col;
        // then y
        for ( int r = 0; r < h ; ++r)
        {
             col.push_back(std::unique_ptr<sf::Sprite>(new sf::Sprite()));
        }
        // Now add the column vector.
        map.push_back(std::move(col));
    }
    return 0;
}