无法从另一个函数访问文件范围变量的内容

时间:2017-07-25 06:46:34

标签: c++ recursion

我有2个函数,其中一个是递归的。这是真正的代码:

class Graph {
public:
    Graph(int v);
    virtual ~Graph();

    void addEdge(int v, int w);

    /**
     * main function that finds and checks SCC
     */
    bool checkSCC();

    /**
     * function that returns reverse (or transpose) of this graph
     */
    Graph getTranspose();
private:
    int V;
    std::list<int> *adj;
    std::vector<int> scc;

    /**
     * fills stack with vertices (in increasing order of finishing times).
     * the top element of stack has the maximum finishing time.
     */
    void fillOrder(int v, bool visited[], std::stack<int> &stack);

    /**
     * a recursive function to print DFS starting from v
     */
    void DFSUtil(int v, bool visited[]);
};

Graph::Graph(int v) {
    this->V = v;
    adj = new std::list<int>[v];
}

Graph::~Graph() {
}

void Graph::addEdge(int v, int w) {
    adj[v].push_back(w);
}

bool Graph::checkSCC() {
    std::stack<int> stack;

    bool *visited = new bool[V];
    for(int i=0; i<V; i++)
        visited[i]=false;

    for(int i=0; i<V; i++)
        if(visited[i]==false)
            fillOrder(i, visited, stack);

    Graph gr = getTranspose();

    for(int i=0; i<V; i++)
        visited[i]=false;

    while(stack.empty() == false){
        int v = stack.top();
        stack.pop();

        if(visited[v]==false){

            if(scc.size() > 1) { /*NOTE the problem is HERE !*/
                return true;
            }

            gr.DFSUtil(v, visited);
        }
    }

    return false;
}

Graph Graph::getTranspose() {
    Graph g(V);
    for(int v=0;v<V;v++){
        std::list<int>::iterator i;
        for(i=adj[v].begin();i!=adj[v].end();++i)
            g.adj[*i].push_back(v);
    }
    return g;
}

void Graph::fillOrder(int v, bool visited[], std::stack<int>& stack) {
    visited[v] = true;

    std::list<int>::iterator i;
    for(i = adj[v].begin(); i!= adj[v].end(); ++i)
        if(!visited[*i])
            fillOrder(*i, visited, stack);

    stack.push(v);
}

void Graph::DFSUtil(int v, bool visited[]) {
    visited[v] = true;
    scc.push_back(v); /*NOTE scc only works in this function !! */
    std::cout << v << " ";

    std::list<int>::iterator i;
    for(i = adj[v].begin(); i != adj[v].end(); ++i)
        if(!visited[*i])
            Graph::DFSUtil(*i, visited);
}

在这段代码中,如果我调用Graph :: checkSCC,scc保留它在Graph :: DFSUtil范围内的内容,但不在Graph :: checkSCC !!为什么会这样?

我感谢任何想法和建议。

1 个答案:

答案 0 :(得分:1)

您在一个对象上调用checkSCC,在DFSUtil创建的另一个对象gr上调用checkSCC

一个scc成员与另一个scc成员无关。