gpt4 book ai didi

c++ - 需要帮助理解 std::find 算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:18:01 25 4
gpt4 key购买 nike

我正在使用 C++。我使用 std::find 算法在我的项目中使用了一段对我有用的代码。它有效,但我不完全理解它。我希望有人能帮忙解释一下,并将这个基本循环重写为基于范围的 for 循环。我使用的代码是:

if (std::find(closedList.begin(), closedList.end(), c.m_next) == closedList.end())
{
openList.push_back(c.m_next);
}

我的理解是该算法在 closedList(使用 容器的列表)的开头和结尾之间搜索 c.m_next。我试图将其重写为:

for (Node* node : closedList)
{
if (node == c.m_next)
{
openList.push_back(node);
}
}

但是我的代码在重写为 for each 循环时不起作用。对我来说,这些看起来是一样的。我是否正确理解了 std::find 算法?如果不是,有人可以通过将其重写为某种 for 循环来帮助向我解释吗?

在代码的例子中,c 是边列表中的一条边。c.m_next 是边的目的节点。closedList是要处理的节点列表。

感谢您的宝贵时间和帮助。

最佳答案

如果不在关闭列表中,原始代码将“节点”添加到 openList。如果它在 closedList 中,您的代码会将“节点”添加到 openList。

If no elements match, the function returns last.

http://www.cplusplus.com/reference/algorithm/find/

您可能希望它与 for each 循环的行为相匹配。

bool isInClosedList = false;
for (Node* node : closedList)
{
if (node == c.m_next)
{
isInClosedList = true;
break;
}
}

if (!isInClosedList)
openList.push_back(node);

关于c++ - 需要帮助理解 std::find 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38089286/

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