Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

C++0x question: Range-based loop and auto

14 views
Skip to first unread message

Juha Nieminen

unread,
Mar 12, 2010, 7:51:42 PM3/12/10
to
With the next standard it will become possible to write eg.

for(int& value: someContainer) { someFunc(value); }

However, would this be valid as well:

for(auto& value: someContainer) { someFunc(value); }

?

That would be useful if the element type is complicated or unknown.

--- news://freenews.netfront.net/ - complaints: ne...@netfront.net ---

Johannes Schaub (litb)

unread,
Mar 12, 2010, 8:13:38 PM3/12/10
to
Juha Nieminen wrote:

> With the next standard it will become possible to write eg.
>
> for(int& value: someContainer) { someFunc(value); }
>
> However, would this be valid as well:
>
> for(auto& value: someContainer) { someFunc(value); }
>
> ?
>
> That would be useful if the element type is complicated or unknown.
>

Yes, that's possible. The declaration will be placed on the left, with a "="
separated from the "*iterator" dereferencing the current iterator.

Alf P. Steinbach

unread,
Mar 12, 2010, 9:10:53 PM3/12/10
to
* Johannes Schaub (litb):

Goodie, but could someone please explain this notation?


Cheers,

- Alf

Juha Nieminen

unread,
Mar 13, 2010, 6:03:53 AM3/13/10
to

If 'someContainer' above is either a static array (ie. one whose size
can be determined at compile time, like you would do with sizeof()) or
an object having a begin() and an end() member function, then the
special for loop syntax above will iterate over the container, with the
reference pointing to the array element or deferenced iterator at each
iteration.

It's simply a shorthand syntax. Nothing you couldn't do more verbosely
in the exact same way as you do today.

Thomas J. Gritzan

unread,
Mar 13, 2010, 7:13:38 PM3/13/10
to

From N3035 (current working draft), 6.5.4:

for (/declaration/ : /expression/) /statement/

is equivalent to:

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

So, it's a simple for-each statement that uses std::begin / std::end
which defaults to calling begin/end member functions (or first /
one-past-last pointer in case of an array).

--
Thomas

Alf P. Steinbach

unread,
Mar 13, 2010, 7:42:10 PM3/13/10
to
* Thomas J. Gritzan:

Thanks, both Thomas and Juha.

Cheers,

- Alf

0 new messages