c++11中基于范围的for

2021-12-11 00:00:00 gcc for-loop c++ c++11

在 C++ 11 中,如果我们有一个 set;S;我们可以说:

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

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

但是我们可以强制 i 成为迭代器吗,我的意思是写一段代码,相当于:

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;

或者我们可以做一些我们可以理解i在集合(或向量)中的索引的事情吗?

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

另一个问题是我们怎么能说不对 S 中的所有元素都这样做,而是对它们的前半部分或除第一个之外的所有元素都这样做.

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.

或者当我们有一个 vector;V,想打印它的第一个n值怎么办?我知道我们可以创建一个新的向量,但是将一个向量复制到一个新的向量需要时间.

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:

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

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

其中 __range、__begin 和 __end 是仅为说明而定义的变量

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

换句话说,它已经从 begin 迭代到 end 并且已经解引用了迭代器,这是你永远看不到的.

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

相关文章