我对使用 Boost 的 C++ 还很陌生。
我希望类“world”的对象有一个名为“chunk”且类型为“octreenode”的数组。以前我有一个普通的一维数组,效果很好。现在,我正在尝试使用具有 Boost 的 multi_array 功能的 3D 数组,但我真的不确定自己做错了什么。
简化代码:
class world {
public:
typedef boost::multi_array<octreenode, 3> planetchunkarray; // a boost_multi for chunks
typedef planetchunkarray::index index;
planetchunkarray *chunk;
world(double x,double y,double z,
int widtheast, int widthnorth, int height) :
originx(x), originy(y), originz(z),
chunkseast(widtheast), chunksnorth(widthnorth), chunksup(height) {
chunk = new planetchunkarray(boost::extents[chunksnorth][chunkseast][chunksup]);
planetchunkarray::extent_gen extents;
for (int cz = 0; cz < chunksnorth; ++cz) {
for (int cx = 0; cx < chunkseast; ++cx) {
for (int cy = 0; cy < chunksup; ++cy) {
(*chunk)[cz][cx][cy] = new octreenode(1,72);
}
}
}
}
};
之后如果我尝试进行分配
root->planet[0]->chunk[0][0][0]->material = 4;
我得到错误:
error: base operand of '->' has non-pointer type 'boost::detail::multi_array::sub_array<octreenode, 1u>'|
“octreenode”有相关的构造函数,并且这一行以相同的语法工作,只是:
root->planet[0]->chunk[0]->material = 4;
(带有一维数组)。类似地,虽然它用一维数组编译得很好,但试图将 block 传递给需要指向“octreenode”对象的指针的函数,例如:
compactoctree(root->planet[p]->chunk[cz][cx][cy], 0, 14);
产生错误
error: cannot convert 'boost::detail::multi_array::sub_array<octreenode, 1u>' to 'octreenode*' for argument '1' to 'short int compactoctree(octreenode*, int, int)'|
非常感谢任何建议,我确信我遗漏了一些明显的东西。
最佳答案
你的数组是值类型(octreenode
),不是指针类型(octreenode*
)
因此,您不应该尝试将指针分配给动态分配的八叉树节点(默认情况下,new
用于堆分配)。
相反,只需分配一个值:
(*chunk)[cz][cx][cy] = octreenode(1,72);
事实上,也没有理由首先在多数组上使用 new
:
更新
在评论中,有人提出可以优化更多内容,并且您认为对有关编译错误的答案进行有用的补充。
所以这里是:如果你确实想用完全相同的值初始化所有数组元素,
您可以通过暂时忘记数组形状来 boost 循环的效率:
std::fill_n(chunk.data(), chunk.num_elements(), octreenode {1, 72});
如果您知道
octreenode
是 POD 类型,您可以编写std::uninitialzed_fill_n(chunk.data(), chunk.num_elements(), octreenode {1, 72});
但是智能库实现最终还是会调用
fill_n
(因为没有 yield )。如果octreenode
不是 POD 类型,但它 可以轻易破坏,则可以使用uninitialized_fill_n
。事实上,首先也没有理由在 multi 数组上使用 new。您可以只使用构造函数初始化列表来构造 multi_array 成员
#include <boost/multi_array.hpp>
#include <type_traits>
struct octreenode { int a; int b; };
class world {
public:
world(double x, double y, double z, int widtheast, int widthnorth, int height)
:
originx(x), originy(y), originz(z),
chunkseast(widtheast), chunksnorth(widthnorth), chunksup(height),
chunk(boost::extents[chunksnorth][chunkseast][chunksup])
{
octreenode v = { 1, 72 };
std::fill_n(chunk.data(), chunk.num_elements(), v);
}
private:
double originx, originy, originz;
int chunkseast, chunksnorth, chunksup;
typedef boost::multi_array<octreenode, 3> planetchunkarray; // a boost_multi for chunks
typedef planetchunkarray::index index;
planetchunkarray chunk;
};
int main() {
world w(1,2,3,4,5,6);
}
关于c++ - 指向动态分配的 boost multi_array 中的类的指针,而不是编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12574682/