2014-02-18 163 views
0

我必须为一个类制作一个六角板,并且我的代码有问题。我的图形有一个用于电路板的2D节点。每个节点都有一个邻居节点的向量。我似乎无法将邻居节点分配到向量中。C++矢量对象:分配对象

节点类:

class node{ 
public: 
    string hex_type = "E";// empty to start 
    vector<node> neighbors; 
    int Xcoordinate; 
    int Ycoordinate; 



class graph{ 
public: 
    int size; 
    graph() { this->size = 11; } 
    graph(int a){ this->size = a; } 
    vector<vector<node> > nodes; 

void initialize(){ 
     int x, y; 
     int max = this->size-1; 
     this->nodes = vector<vector<node> >(size, vector <node>(size)); 
     for (x = 0; x < size; ++x){ 
      for (y = 0; y < size; ++y){ 
       //this->nodes[x][y] = node(); 
       this->nodes[x][y].Xcoordinate = x; 
       this->nodes[x][y].Ycoordinate = y; 
       this->nodes[x][y].neighbors = vector<node>(6); 
       if ((x == 0) && (y == 0)){ this->nodes[x][y].neighbors[0] = this->nodes[x + 1][y]; } 

       } 

      } 
     } 
}; 

我打印语句这里只输出了一系列数字:-842150451

cout << this->nodes[0][0].neighbors[0].Xcoordinate; 
+0

这是正确的。 –

+0

那XCoordinate怎么样? – dkimmel7

回答

0

当这个 - >节点[X] [Y] .neighbors [0] =这个 - >节点[X + 1] [Y];被执行,x = 0,y = 0。节点[1] [0]没有初始化。 您可以先初始化所有节点。

for (x = 0; x < size; ++x){ 
      for (y = 0; y < size; ++y){ 
       //this->nodes[x][y] = node(); 
       this->nodes[x][y].Xcoordinate = x; 
       this->nodes[x][y].Ycoordinate = y; 
      } 
     } 
for (x = 0; x < size; ++x){ 
      for (y = 0; y < size; ++y){ 
       //this->nodes[x][y] = node(); 
       this->nodes[x][y].neighbors = vector<node>(6); 
       if ((x == 0) && (y == 0)){ this->nodes[x][y].neighbors[0] = this->nodes[x + 1][y]; } 
      } 
     } 
0

.neighbors[0] = this->nodes[x + 1][y];多数民众赞成制作拷贝节点的。尚未初始化的节点的副本。 Ergo副本具有无意义的价值。

你可能想要vector<node*> neighbors;,所以它保存指向它的邻居而不是副本的指针。

如果是这样,这将是

.neighbors[0] = &(this->nodes[x + 1][y]); 
       ^
+0

这行代码:this-> nodes [x] [y] .neighbors [0] = this-> nodes [x + 1] [y]会变成.....? – dkimmel7