Ranged-based for Loop
With C++11, operating on data sets is easy to do with highly readable code, as long as the container supports iterators.
For example when dealing std::map
:
for( auto item : items ) {
// item.first is the key, and
// item.second is the value
cout << item.first << " = " << item.second;
}
To access a copy of the data set read-only, use const
keyword:
for( const auto item : items ) {
}
To modify the data set if it is modifiable, add &
:
for( auto& item : items ) {
}
The const
and auto
keywords takes away a lot of typing, the resulting code fragments reads similarly to scripting languages with same functionality.
Update
Generally we want to avoid copying the data for better performance, therefore as explained on StackExchange it is better to use:
for( auto&& item : items ) {
}