c++ - 没有计数器的for循环的可读性

标签 c++ loops for-loop while-loop readability

我最近为一个简单的链表写了一个实现,在我的代码中有几个地方看起来像

Node* current_node = head;
while (current_node != nullptr) {
    if (current_node->data == query) {
    // perform some action
    break;
    }
current_node = current_node->next;
}

我最近才想到我可以将其重新实现为

for (Node* current_node = head; current_node != nullptr; current_node = current_node->next) {
    if (current_node->data == query) {
    // perform some action
    break;
    }
}

我知道两者在语法上都是正确的,任何性能差异都可以忽略不计,但我想知道检查中的相等条件是否通常在 for 循环中实现?以前我只在 for 循环中使用不等式(例如:>、< 等)。哪个版本更传统/更易读?

最佳答案

通过 for 循环遍历链表并不是一个坏习惯,但您可以将其改进为:

std::list<type> list;
auto it = std::find(begin(list), end(list), query);
if (it != end(list))
    // perform some action

关于c++ - 没有计数器的for循环的可读性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35188726/

相关文章:

java - 如果函数不是递归的,while 可以用 if 代替吗?

c - for循环中的数组未获得正确的值

c++ - 为什么 if constexpr 不会使这个核心常量表达式错误消失?

C++ 符号在共享对象中具有不同的大小

c++ - 如何在 C++ 中读取和解析 CSV 文件?

c - 如何将一个指针指向的地址分配给另一个本地指针

c++ - 在循环中从 unordered_set 中删除元素时崩溃

c++ - 是否可以在我的对象上停止 std::addressof?

r - 向量化包含循环和 if 子句的搜索函数

java - 向后寻求处理无效的 MP3 header ?