可以在循环中使用 C++ STL 的这个函数 queue::size() 影响行为

Can using this function queue::size() of C++ STL in loop affect behaviour

我正在为二叉树的左视图编写代码。在循环中,当我将条件设置为 i<q.size() 时,我得到不同的(错误的)输出,当将其存储在变量中并在循环中使用该变量时,Like

int size = q.size();
for(int i=0; i<size; i++)

我在使用上面的代码时得到了正确的输出。 为什么会这样?

代码:

#include<queue>
using namespace std;

struct Node{
    struct Node *left;
    struct Node *right;
    int data;
    Node(int val){
        left = NULL;
        right = NULL;
        data = val;
    }

};

void leftView(Node *root){
    queue<Node*> q;
    q.push(root);

    while(!q.empty()){
        int size = q.size();
        for(int i=0; i<size; i++){
            Node *curr = q.front();
            q.pop();

            if(curr->left) q.push(curr->left);
            if(curr->right) q.push(curr->right);

            if(i==0) cout<<curr->data;
        }
        
    }
}
int main(){

    struct Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->left = new Node(6);
    root->right->left->left = new Node(9);
    root->right->right = new Node(7);
    leftView(root);
}

代码确实有不同的行为:

int size = q.size();
for(int i=0; i<size; i++)
for(int i=0; i<q.size(); i++)

第一个版本有一定的循环大小:当前队列的大小。第二个有一个动态循环大小,它不是确定性的,因为在循环中我们可以将元素推入队列或从队列中弹出元素,然后每次我们评估 q.size,我们得到一个不同的大小。所以第二个版本大部分是错误的,没有用的。

你的代码实现了二叉树的层级遍历,对于每一层,需要访问的节点是当前队列的大小,所以第一个版本给了我们正确答案。