对象的C ++向量:分配对象

时间:2014-02-18 01:18:09

标签: c++ vector graph

我必须为类创建一个hex板,我的代码有问题。我的图表有一个用于电路板的2D矢量节点。每个节点都有一个邻居节点的向量。我似乎无法将邻居节点分配到向量中。

节点类:

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]; }

                }

            }
        }
};

我的print语句只输出一系列数字:-842150451

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

2 个答案:

答案 0 :(得分:0)

.neighbors[0] = this->nodes[x + 1][y];正在制作节点的副本。您尚未初始化的节点的副本。因此副本具有无意义的值。

您可能想要vector<node*> neighbors;,因此它会指向它的邻居,而不是副本。

如果是,那就是

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

答案 1 :(得分:0)

当this-&gt; nodes [x] [y] .neighbors [0] = this-&gt; nodes [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]; }
            }
        }