简体   繁体   English

基于范围的 for 循环 vs 常规迭代器 for 循环

[英]range based for loop vs regular iterator for loop

Consider the following code example :考虑以下代码示例:

#include<iostream>
#include<vector>
#include<typeinfo>

int main(){
    std::vector<int> v = {1 ,2,4};
    for(auto &i:v)  std::cout<<typeid(i).name();
    for(auto k = v.begin(); k!=v.end();++k) std::cout<<typeid(k).name();
    return 0;
}

The first loop represents range based for-loops , and second one are regular for loops with iterators.第一个循环代表基于范围的 for-loops ,第二个循环是带有迭代器的常规 for 循环。 I have used regular ones a lot , and from my experience , auto k is of type of iterator , while range based loops had type of auto i as int.我经常使用常规的,根据我的经验, auto k是迭代器类型,而基于范围的循环的auto i类型为 int。 Output of above program is:上述程序的输出是:

i & N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE i & N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE

Is this normal behavior for range based for loops over collections like vectors ( somewhere mentioned) ?这是基于范围的循环对像向量这样的集合(某处提到)的正常行为吗? Because someone (like me) would assume range based for loops are just shorthand for regular for loops.因为有人(像我一样)会假设基于范围的 for 循环只是常规 for 循环的简写。

The answer is what Magnus already stated: Yes, it is a normal behavior .答案是 Magnus 已经说过的:是的,这是正常行为 Range loops are for cases when we are interested in examining every item in a collection (unless we break out sooner) and aren't interested in doing anything with the container itself.范围循环适用于我们有兴趣检查集合中的每个项目(除非我们早点突破)并且对容器本身做任何事情不感兴趣的情况。 Like it was already stated, range loops are optimized that way , eg it indeed computes the finishing condition only once.就像已经说过的那样,范围循环以这种方式进行了优化,例如,它确实只计算了一次完成条件。 In my opinion, this is a very nice and welcome addition to the variety of loop options in c++, since we do often face this very exact situation: we get a container and are interested in simply going through them one by one in either const or non-const fashion.在我看来,这是对 C++ 中各种循环选项的一个非常好的和受欢迎的补充,因为我们确实经常面临这种非常确切的情况:我们得到一个容器,并且有兴趣简单地在 const 或非常规时尚。

range based for loop will give container element.基于范围的 for 循环将给出容器元素。

exa:例如:

vectorv{5,7,10}; vectorv{5,7,10};

for(auto i:v)对于(自动 i:v)

cout<<i ; cout<<i; //5,7,10 //5,7,10

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

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