C++ c++;唯一_ptr对象的二维数组?

C++ c++;唯一_ptr对象的二维数组?,c++,arrays,pointers,C++,Arrays,Pointers,我试图创建一个简单的二维数组或SFML的精灵对象向量。我尝试了很多不同的方法,结果总是出错或者只是一个空向量 我试过了 // 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) {

我试图创建一个简单的二维数组或SFML的精灵对象向量。我尝试了很多不同的方法,结果总是出错或者只是一个空向量

我试过了

// 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()));
    }
}
//第一个x
对于(int c=0;c

unique_ptr映射;
...
map.reset(唯一的ptr(新的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;
}
#包括
#包括
命名空间sf{class Sprite{};}
int main()
{
常数int w=5;
常数int h=5;
//精灵的向量就是你要找的
std::矢量地图;
//第一个x
对于(int c=0;c
然后将其设为[静态]成员变量或在命名空间中定义。注意:不应创建精灵的2D数组。您应该创建一个1D精灵数组,其宽度*高度
与2D数组一样,您可以访问该数组。这是创建
std::unique\u ptr
2D数组的最短方法吗?我也有同样的想法,但我有一种强烈的感觉,那就是应该有更好的东西存在。没有比这更地道的了吗?
#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;
}