[英]How to initialize a Vector within a struct for a node
我的問題如下:
我正在制作一個帶有內部節點的 KD 樹,如下所示:
struct internalNode {
int DimForDisc; //Dimension For Discrimination
int ValForDisc; //Value For Discrimination
internalNode* leftChild, * rightChild;
vector<vector<int>> leftLeaf;
vector<vector<int>> rightLeaf;
};
作為此過程的一部分,我需要在創建新節點時初始化 vector<vector>。 我當前的代碼如下所示:(由於限制,我必須使用 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>>
如果我嘗試執行以下操作,則使用上述實現會導致分段錯誤:
vector<vector<int>> leftLeaf;
vector<vector<int>> rightLeaf;
PointerToNode->leftLeaf = leftLeaf;
PointerToNode->rightLeaf = rightLeaf;
它會導致 SIGABRT 並說 free(): invalid size 如果我嘗試完全忽略初始化向量,那么我會收到以下錯誤:
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 需要手動構建小瓶放置 new,並通過顯式析構函數調用直接銷毀。 IE
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);
That said, I discourage trying to mix C and C++ memory allocation and object management functions, and would suggest an official protest against using new
properly, if not ideally using smart pointers in the first place.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.