简体   繁体   English

不带计数器的for循环的可读性

[英]Readability of for-loops without counters

I recently wrote an implementation for a simple linked list, and at several points in my code it looks like 我最近为一个简单的链表编写了一个实现,在我的代码中的几点看来

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

And I just recently thought I could re-implement this as 我最近认为我可以重新实现为

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

I know that both are syntactically correct, and that any performance differences should be negligible, but I was wondering if having an equality condition in the check is generally implemented in a for-loop? 我知道两者在语法上都是正确的,并且任何性能差异都应该忽略不计,但是我想知道在检查中是否具有相等条件通常是在for循环中实现的吗? Previously I have only used inequalities (ex: >, <, etc.) in for-loops. 以前,我只在for循环中使用不等式(例如:>,<等)。 Which version is more conventional/readable? 哪个版本更常规/可读?

It's not a bad practice to loop through a linked list via for loop, but you can improve it to: 通过for循环遍历链接列表并不是一个坏习惯,但是您可以将其改进为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM