给定一个 vector ,vc,
可以迭代具有范围的 vector :
for (auto c : vc)
std::cout << c;
或者使用迭代器:
for (auto it = vc.cbegin(); it != vc.cend(); ++it)
std::cout << *it;
是否有使用一种方法而不是另一种方法的功能原因,或者这仅仅是风格问题?
最佳答案
从性能的角度来看,并没有真正的区别。正如 Bjarne Stroustrup 在他的《C++ 编程语言第 4 版》一书中所写:
The simplest loop is a range- for -statement; it simply gives the programmer access to each element of a range.
作为 KISS 原则的拥护者,我倾向于更喜欢更简单的结构而不是更复杂的结构。然而,它真的归结为你想要实现的目标。 Bjarne 在同一本书中揭示了为什么将 range-for 循环设计得简单:
Note that a range- for loop is a deliberately simple construct. For example, using it you can’t touch two elements at the same time and can’t effectively traverse two ranges simultaneously. For that we need a general for-statement.
因此,有些情况下您不能使用范围 for 循环,您必须驻留在经典的 for 语句中。
底线尽可能使用 range-for 循环,因为它更简单且更具可读性。
关于c++ - 是否应该使用范围 for 循环而不是 vector 上的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35417360/