Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

algorithm - Unexpected result of my DFS tree (C++)

I have solved this problem!!! I found that if i have to use vector<Node*> children;. But I am not very sure the reason, can someone tell me why? Thanks:)

Question:

I use test.cpp to generate a tree structure like:

enter image description here

The result of (ROOT->children).size() is 2, since root has two children.

The result of ((ROOT->children)[0].children).size() should be 2, since the first child of root has two children. But the answer is 0, why? It really confuse for me.

test.cpp (This code is runnable in visual studio 2010)

#include <iostream>
#include <vector>
using namespace std;

struct Node {
    int len;
    vector<Node> children;
    Node *prev;
    Node(): len(0), children(0), prev(0) {};
};

class gSpan {
public:
    Node *ROOT;
    Node *PREV;
    void read();
    void insert(int);
};

int main() {
    gSpan g;
    g.read();
    system("pause");
}

void gSpan::read() {
    int value[4] = {1, 2, 2, 1};
    ROOT = new Node();
    PREV = ROOT;
    for(int i=0; i<4; i++) {
        insert(value[i]);
    }
    cout << "size1: " << (ROOT->children).size() << endl; // it should output 2
    cout << "size2: " << ((ROOT->children)[0].children).size() << endl; // it should output 2
    system("pause");
}

void gSpan::insert(int v) {

    while(v <= PREV->len)
        PREV = PREV->prev;
    Node *cur = new Node();
    cur->len = v;
    cur->prev = PREV;
    PREV->children.push_back(*cur);
    PREV = cur;

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that you children vector contains Node values rather than Node* pointers. While your access uses the root correctly, it finds only copies of the children you try to maintain. All of your nodes are also leaked.

You might want to use a std::vector<Node*> for your children and delete them at some point. The easiest way is probably to use a vector of smart pointers, e.g. a teference counted pointer, and have the smart pointer take care of the release.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...