c++ 2d unique_ptr对象数组
c++ 2d array of unique_ptr objects?
我正在尝试创建一个简单的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;
}
相关文章:
- 将对象数组的引用传递给函数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 类对象数组的问题会导致崩溃
- Arduino C++在构造函数中用参数声明对象数组
- 使用对象数组对 SFML 进行动画处理
- C++ 对象数组堆栈溢出
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何初始化对象数组?
- C++创建对象数组
- 在对象数组中搜索字符串并返回相应值的函数
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- 使用 C++ 创建对象数组
- 对象数组打印空白字符串
- 重载运算符 [] 用于从对象数组中给出特定索引
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组