gpt4 book ai didi

c++使用foreach使数组为空

转载 作者:行者123 更新时间:2023-11-30 00:43:38 28 4
gpt4 key购买 nike

Node* nodes[3];

for (Node* eachNode:nodes) {
eachNode = 0; //if i try to dereference it gives seg fault
} // eg. *eachNode = 0;

if (nodes[0] == 0) {
cout << "Null";
} else
cout << "Not null";

cout << '\n';

Node* nodes2[3];

for (int i = 0; i < 3; ++i) { //this way works fine
nodes2[i] = 0;
}

if (nodes2[0] == 0) {
cout << "Null";
} else
cout << "Not null";

大家好,我正在尝试使数组中的所有对象都为 null。使用 for 循环时它工作正常,但当我使用 foreach 循环时它会中断。

我得到的输出是

不为空

我认为我必须取消引用 foreach 循环中的节点,但它会出现段错误。

有人知道怎么回事吗?谢谢。

最佳答案

您编写的循环遍历数组的:

for (Node* eachNode:nodes) {
eachNode = 0;
}

上面的循环也可以使用 auto 编写:

for (auto eachNode:nodes) {
eachNode = 0;
}

上述循环的问题在于,eachNode 不是存储在数组中的指针,而是存储在循环的局部变量中的该指针的拷贝。

如果您希望将节点设置为空,您需要对要设置它的内存位置的引用。您可以通过使用 auto& 引用数组元素来获取该引用:

for (auto& eachNode:nodes) {
eachNode = 0;
}

这最后一段可能会做你想做的。

关于c++使用foreach使数组为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53096733/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com