我正在創建一個由分支組成的樹。爲了我的工作目的,我需要跟蹤分支,爲了做到這一點,我想將它們存儲在向量列表中。我將vector-list作爲全局變量存儲在此文件中,因爲我想在構造函數和下面的代碼片段中顯示的函數中使用它。如何將矢量列表存儲爲全局變量?
這裏比較棘手的部分是,我收到一條錯誤消息(在Visual Studio 2013中運行),據我所知可能與迭代器沒有正常工作有關。每當我調用branchList.push_back(root)和branchList.resize()時都會出現錯誤消息。 branchList.size()不會導致錯誤。
所以我的問題是:我錯過了什麼/不理解,使這項工作?如果我要放置向量branchList;在構造函數的開始,一切都按預期工作。但是這對我沒有幫助,因爲我以後需要在其他功能中使用它。
我正在使用的文件中的相關代碼片段。
skeletonBuilder.h:
class TreeSkeleton {
public:
TreeSkeleton();
void growTree();
};
skeletonBuilder.cpp:
#include "skeletonBuilder.h"
#include <cstdint>
#include <vector>
typedef struct branch {
branch *parent;
vec3 position;
vec3 direction;
} branch;
//used by constructor + "treeGrow" function
std::vector<branch> branchList = {};
TreeSkeleton::TreeSkeleton() {
//instantiate the tree root as a starting position.
branch root;
root.parent = NULL;
root.position = vec3(0, 0, 0);
root.direction = vec3(0, 1, 0);
branchList.size(); //works fine
branchList.resize(100); //Crashes here
branchList.push_back(root); //Crashes here
}
TreeSkeleton::growTree() {
//pushing more branches to branchList
}
main.cpp中:
#include "skeletonBuilder.h"
TreeSkeleton tree;
int main(int argc, char *argv[]) {
return 0;
}
該錯誤消息我得到:
Unhandled exception at 0x00507077 in OpenGL_project_Debug.exe: 0xC0000005: Access violation reading location 0x40EAAAB4.
錯誤消息帶我到下面的代碼片斷在一個名爲「矢量」文件:
#if _VECTOR_ORPHAN_RANGE
void _Orphan_range(pointer _First, pointer _Last) const
{ // orphan iterators within specified (inclusive) range
_Lockit _Lock(_LOCK_DEBUG);
const_iterator **_Pnext = (const_iterator **)this->_Getpfirst();
if (_Pnext != 0)
while (*_Pnext != 0) //<----------------This is the row that it gets stuck on
if ((*_Pnext)->_Ptr < _First || _Last < (*_Pnext)->_Ptr)
_Pnext = (const_iterator **)(*_Pnext)->_Getpnext();
else
{ // orphan the iterator
(*_Pnext)->_Clrcont();
*_Pnext = *(const_iterator **)(*_Pnext)->_Getpnext();
}
}
請複製粘貼你得到 – UnholySheep