如何在结构中为节点初始化Vector



我的问题如下:

我正在制作一个具有内部节点的KD树,如下所示:

struct internalNode {
int DimForDisc; //Dimension For Discrimination
int ValForDisc; //Value For Discrimination
internalNode* leftChild, * rightChild;
vector<vector<int>> leftLeaf;
vector<vector<int>> rightLeaf;
};

作为该过程的一部分,我需要初始化向量<矢量>当我创建一个新节点时。我目前的代码如下所示:(由于限制,我必须使用malloc/创建我自己的构造函数(

internalNode* makeInternalNode(int DimForDisc, int ValForDisc,
internalNode* leftChild, internalNode* rightChild) {
internalNode* PointerToNode = (internalNode*)malloc(sizeof(internalNode));
PointerToNode->DimForDisc = DimForDisc;
PointerToNode->ValForDisc = ValForDisc;
PointerToNode->leftChild = leftChild;
PointerToNode->rightChild = rightChild;
PointerToNode->leftLeaf.clear();
PointerToNode->rightLeaf.clear();
return(PointerToNode);
}

有一次,在创建节点后,我试图通过执行Root->leftLeaf = AccumulatedData;将leftLeaf设置为等于另一个vector<vector<int>>。在上面的实现中,如果我尝试执行以下操作,则会导致Segmentation错误:

vector<vector<int>> leftLeaf;
vector<vector<int>> rightLeaf;
PointerToNode->leftLeaf = leftLeaf;
PointerToNode->rightLeaf = rightLeaf;

它会导致SIGABRT并说free((:无效大小如果我试图完全忽略初始化向量,那么我会得到以下错误:

Program received signal SIGSEGV, Segmentation fault.
0x0000555555558b76 in std::vector<int, std::allocator<int> >::capacity (this=0xc3b00001716) at /usr/include/c++/9/bits/stl_vector.h:996
996           { return size_type(this->_M_impl._M_end_of_storage

我想的都试过了,但都无济于事。我已经确认AccumulatedData保存了正确的信息,所以问题确实出现在试图将其复制到InternalNode的结构中时。任何帮助都将不胜感激,可以根据需要添加更多信息。

尽管使用malloc/free是一个可怕的想法,但需要手动构建新的小瓶,并通过显式析构函数调用直接销毁。即

internalNode* makeInternalNode(int DimForDisc, int ValForDisc,
internalNode* leftChild, internalNode* rightChild) {
internalNode* PointerToNode = (internalNode*)malloc(sizeof(internalNode));
new (PointerToNode) internalNode;
PointerToNode->DimForDisc = DimForDisc;
PointerToNode->ValForDisc = ValForDisc;
PointerToNode->leftChild = leftChild;
PointerToNode->rightChild = rightChild;
// vectors are born clear, so I removed those superfluous executions.
return(PointerToNode);
}

稍后在销毁时间(无论在哪里(,你必须这样做:

PointerToNode->~internalNode();
free(PointerToNode);

也就是说,我不鼓励尝试混合使用C和C++内存分配和对象管理功能,并建议正式抗议正确使用new,如果一开始就不理想地使用智能指针的话。

最新更新