我应该使用迭代器而不是基于范围的循环吗?如果是这样,为什么?

Should I use for iterators instead of for range based loop, if so, why?

什么是最好的,基于范围的 for 循环?

for (auto& i : just_a_vec )

或者循环迭代器?

for (std::vector<std::string>::iterator it = just_a_vec.begin(); it < just_a_vec.end(); it++)

个人快速回答:它有点系统化,并且基于您使用的 c++ 版本。我通常更喜欢基于范围的,但当然也有迭代器也会大放异彩的时刻。将两者都添加到您的工具箱中。进一步阅读。

这是其他 SO 答案的列表,这些答案更多地涉及性能和用例。

  • Is the ranged based for loop beneficial to performance?

了解更多信息。 Google

Range vs iterator loop c++

迭代器早于基于范围的 for 循环,因此它们曾经是这两种替代方法中唯一可用的。如今,在处理简单循环时,基于范围的 for 基本上取代了迭代器。

但是,迭代器也可以在其他各种上下文中使用。例如,您可以执行 std::sort(v.begin(), std::next(v.begin(), 5)) 对向量的前五个元素进行排序,而保留其余元素。

回到遍历整个容器:

  • 如果您可以使用基于范围的 for 来完成您想要的,那么它会导致代码更清晰,因此默认情况下它们更可取。

  • 如果您出于某种原因需要迭代器,例如使用需要它们的算法,或者因为您需要在迭代时向前或向后跳转,请改用它们。

此外:在后一种情况下,您 can/should 在声明迭代器时仍然使用 auto

for(auto it = just_a_vec.begin(); it < just_a_vec.end(); it++) {
}

编辑: 如所问:这是一个简单的示例,如果有点做作,基于迭代器的循环仍然有用:

// adds all values in the vector, but skips over twos values when encountering a 0
// e.g.: {1,2,0,4,5,2} => 5
int my_weird_accum(const std::vector<int>& data) {
  int result = 0; 
 
  for(auto it = data.begin(); it != data.end(); ++it) {
    auto v = *it;
    result += v;

    if(v == 0) {
      // skip over the next two
      assert(std::distance(it, data.end()) > 2);
      std::advance(it, 2);
    }
  }
  return 0;
}