基于范围的循环与常规循环的迭代器 [英] range based for loop vs regular iterator for loop

查看:42
本文介绍了基于范围的循环与常规循环的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码示例:

#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;
}

第一个循环代表基于范围的for循环,第二个循环代表具有迭代器的循环.我经常使用常规的,根据我的经验,auto k是迭代器的类型,而基于范围的循环的auto i类型是int.上面程序的输出是:

The first loop represents range based for-loops , and second one are regular for loops with iterators. 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. Output of above program is:

i& N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE

这种基于范围的for循环的正常行为是在像矢量这样的集合上循环的吗?因为像我这样的人会认为基于范围的for循环只是常规for循环的简写.

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.

推荐答案

答案是马格努斯已经说过:是的,这是正常行为.范围循环适用于以下情况:我们有兴趣检查集合中的每个项目(除非我们尽快推出),并且不希望对容器本身做任何事情.就像已经说过的那样,范围循环是通过这种方式优化的,例如实际上,它仅计算一次精加工条件.在我看来,这是对c ++中各种循环选项的非常好和受欢迎的补充,因为我们经常会遇到这种非常精确的情况:我们得到了一个容器,并且感兴趣的是简单地在const或const中逐一地对其进行遍历.非常量时尚.

The answer is what Magnus already stated: Yes, it is a normal behavior. 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, e.g. 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.

这篇关于基于范围的循环与常规循环的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆