2013-04-22 151 views
1

我想創建一個簡單的二維數組或向量的SFML的Sprite對象。我嘗試了很多不同的方法,最終總是得到錯誤或者只是一個空的向量。C++ unique_ptr對象的2d數組?

我已經試過

// 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數組。所以我需要這個二維數組在創建後離開堆棧等等。

+0

然後將其作爲[靜態]成員變量或在名稱空間中定義它。 – 2013-04-22 02:25:06

+0

注意:您不應該創建精靈的二維數組。你應該創建一個'width * height'長度的精靈的一維數組,你可以像2D數組那樣訪問。 – 2013-04-22 04:52:12

回答

0

您聲明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; 
} 
+0

是製造'std :: unique_ptr'二維數組的最簡單方法嗎?我提出了相同的觀點,但我有強烈的感覺應該有更好的東西存在。沒有更慣用的東西? – 2013-07-18 12:24:34