【问题标题】:C++ vector of objects: assigning the objects对象的 C++ 向量:分配对象
【发布时间】:2014-02-18 01:18:08
【问题描述】:

我必须为一个班级制作一个十六进制板,但我的代码有问题。我的图表有一个板的二维节点向量。每个节点都有一个相邻节点的向量。我似乎无法将邻居节点分配到向量中。

节点类:

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;

【问题讨论】:

  • X坐标怎么样?

标签: c++ vector graph


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    如果是这样,那就是

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

    【讨论】:

    • 代码行:this->nodes[x][y].neighbors[0] = this->nodes[x + 1][y] 会变成.....?
    猜你喜欢
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2021-05-05
    • 2017-12-06
    • 2022-11-17
    • 2021-08-09
    相关资源
    最近更新 更多