基于范围的在c ++ 11中 [英] range-based for in c++11

查看:154
本文介绍了基于范围的在c ++ 11中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个 set< int> S ;我们可以说:

  for(auto i:S)
cout< i<< endl;

但我们可以强制 i 迭代器,我的意思是写一个等价的代码:

  for(auto i = S.begin(); i! S.end(); i ++)
cout< (i!= s.begin())? :< *一世;

或者我们可以做一些我们可以理解 i 在集合(或向量)?



另一个问题是我们怎么可以不这样做的所有元素<$ c $



或者当我们有一个 S ,但前半部分或全部。 > vector< int> V ,并且要打印其第一个 n 值,我们应该怎么办?我知道我们可以创建一个新的向量,但需要时间将一个向量复制到一个新的向量。

解决方案

查看标准的内容:


语句的范围为
for(for-range-declaration:expression)statement
相当于

  {
auto&& __range =(expression);
for(auto __begin = begin-expr,__end = end-expr; __begin!= __end; ++ __ begin){
for-range-declaration = * __ begin;
语句
}
}

其中__range,__begin和__end是只为exposition定义的变量


换句话说,它已经从 begin end ,并且已经解除引用迭代器了,你永远不会看到。


in c++ 11 if we have a set<int> S; we could say:

for (auto i: S)
    cout << i << endl;

but can we force i to be a iterator, I mean write a code that is equivalent to:

for (auto i = S.begin(); i != S.end(); i++)
    cout << (i != s.begin()) ? " " : "" << *i;

or could we do something that we can understand the index of i in the set(or vector)?

and another question is how could we say that don't do this for all elements in S but for first half of them or all of them except the first one.

or when we have a vector<int> V, and want to print its first n values what should we do? I know we can create a new vector but it takes time to copy a vector to a new vector.

解决方案

No, unluckily. See what the standard says:

The range-based for statement for ( for-range-declaration : expression ) statement is equivalent to

{
    auto && __range = ( expression );
    for ( auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin ) {
        for-range-declaration = *__begin;
        statement
    }
}

where __range, __begin, and __end are variables defined for exposition only

In other words, it already iterates from begin to end and already dereferences the iterator, which you never get to see.

这篇关于基于范围的在c ++ 11中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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