打印值输出不一致

问题描述 投票:-1回答:1

在此程序中,我正在用c ++克隆图形。This is the question that i am coding.这是我的程序,下面是问题和问题区域。

#include <vector>
#include <unordered_map>
#include <queue>
#include <iostream>
using namespace std;
#define neighbours neighbors
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> neighbors;

    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }

    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }

    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};

#define neighbours neighbors
class Solution {
public:
    Node* cloneGraph(Node* node) 
    {
        // BFS
        queue <Node*> q;
        // add starting vec
        q.push(node);

        Node *curr;
        int value;
        vector <int> visited;
        unordered_map <int, Node*> umap;

        while(!q.empty())
        {
            curr = q.front();
            q.pop();
            visited.push_back(curr->val);
            //cout << curr->val << "-";
            // create new node
            Node *newNode = new Node(curr->val);
            // add new node val and addr to umap
            umap[value] = newNode;
            // clone neighbour list
            vector <Node*> nlist;
            //vector <Node*> list = curr->neighbours; // make copy of given list
            for(Node* node: curr->neighbours)
            {
                value = node->val;
                //cout << value << " ";
                // search in map first, if exists take addr else make and insert into                   
                // list
                if(umap.find(value) == umap.end())
                {
                    umap[value] = new Node(value);
                }
                nlist.push_back(umap[value]);
                if(find(visited.begin(), visited.end(), value) == visited.end())
                {
                    q.push(node);
                }
            }
            cout << endl;

            newNode->neighbours = nlist; // copy nlist to nodes list part
        }
        // starting of new node = umap[1];
        return umap[1];
    }
};

int main()
{
    Node ob1;
    Node ob2;
    ob1.val = 1;
    ob2.val = 2;
    vector <Node*> nlist;
    nlist.push_back(&ob1);
    ob2.neighbours = nlist;
    nlist.pop_back();
    nlist.push_back(&ob2);
    ob1.neighbours = nlist;
    Solution obj;
    Node *sv = obj.cloneGraph(&ob1);
    cout << sv->val << "-";
    for(Node *node : sv->neighbours)
    {
        cout << node->val << endl;
    }
    cout << &ob1 << " " << sv << endl;
}

当我注释掉我的输出的最后一行是

1-2

当我保持原样时,输出为

1-0x7ffee561e4e0 0x7fb1ba402840

[我也试图注释掉cout << endl;循环的结尾处的while,并且也注释掉了程序的最后一个给出输出的语句

1-

这种奇怪行为的原因是什么?

c++ memory graph iostream cout
1个回答
1
投票

[umap[value] = newNode;显示出未定义的行为,通过访问未初始化的变量value

实际上,value包含一些恰好位于堆栈上的垃圾。对程序看似无关的部分的更改将影响堆栈的内容,进而影响value的初始值,最终影响上述未定义行为的表现方式。]

© www.soinside.com 2019 - 2024. All rights reserved.