【问题标题】:And operator argument evaluation in C++ [duplicate]和 C++ 中的运算符参数评估 [重复]
【发布时间】:2016-04-12 08:07:01
【问题描述】:

and 运算符如何评估其参数。我有一个代码来检查图形是否是循环的。在此代码中,if 语句中有一个 and 条件。而且我认为,据我所知,它在第一次遇到错误表达式时终止,根本不评估第二个表达式。

这是代码

bool Graph::isCyclicUtil(int v, bool *visited, bool *recStack){
    if (visited[v] == false){
            // Mark the current node as visited 
            visited[v] = true;
            recStack[v] = true;

            // Recur for all the vertices adjacent to this vertex
            list<int>::iterator i;
            for (i = adj[v].begin(); i != adj[v].end(); i++){
     -------->**This and cond**if (!visited[*i] && isCyclicUtil(*i, visited, recStack))
                            return true;
                    else if (recStack[*i])
                            return true;
            }
    }
    recStack[v] = false;    // remove the vertex from the recursion stack
    return false;
}

void Graph::printRecStack(bool *recStack){
    cout << "\n \n";
    for (int i = 0; i < V; i++){
            if (recStack[i])
                    cout <<i<< "\n";
    }
    return;
}


bool Graph::isCyclic(){
    // Mark all the vertices as not visited and not part of recursion stack
    bool *visited = new bool[V];
    bool *recStack = new bool[V];
    for (int i = 0; i<V; i++){
            visited[i] = false;
            recStack[i] = false;
    }

    // Call the recursive helper function to detect cycle in different
    // DFS trees.
    if (isCyclicUtil(0,visited, recStack)){
            printRecStack(recStack);
            return true;
    }
    /*for (int i = 0; i < V; i++){
            if (isCyclicUtil(i, visited, recStack))
                    printRecStack(recStack);
                    return true;
    }*/
    return false;
}

请注意isCyclicUtil函数中if语句中的and条件。

如果你把一个简单的图表作为一个像这样的测试用例:

0->1
1->2
2->0
2->3
3->3

并为 0 调用 isCyclicUtil,第一个 3 recStack 中的 值是真的。如果在 if 语句 中也计算了第二个表达式,则情况不应该如此。因为对 node 2 的调用将到达它的 child 0。但是由于循环是从 0 开始的,所以 0 已经被访问过了,所以 recStack[0] 应该被初始化为 false。但这并没有发生,而且所有这些都是真实的。好像 and 条件一遇到 visited[0] 就终止了,甚至没有调用isCyclicUtil(0,visited,recStack)。

【问题讨论】:

  • 在网上搜索“短路评估”。请注意,这仅适用于内置运算符。如果你重载这些操作符,这将被禁用,它们的行为就像常规函数一样。
  • 任何 C++ 书籍或教程都会解释这一点。

标签: c++


【解决方案1】:

没错。这称为short-circuiting,是许多编程语言的特性。

【讨论】:

    猜你喜欢
    • 2013-07-30
    • 1970-01-01
    • 2021-10-03
    • 2011-08-15
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    相关资源
    最近更新 更多