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 ---
> 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.
Goodie, but could someone please explain this notation?
Cheers,
- Alf
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.
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
Thanks, both Thomas and Juha.
Cheers,
- Alf