General features: Ranged-based for loop

code

Syntax

Usage / Usability

  • Already had the stl call: for_each(begin, end, func)
    • Still have to say the begin and the end iterators: but more flexible
    • Hard for cases when you want to do more things in a for (with for_each we need to have it in a function – usually lambdas)

PROS

  • it is possible to iterate over C-like arrays, initializer lists and anything for which the non-member begin() and end() functions are overloaded.
  • useful when you just want to get and do something with the elements of a collection/array and don’t care about indexes, iterators or number of elements.

CONS

  • can’t iterate in reverse
  • don’t offer the index of the current element
  • People will start using them in cases where other options are better (algorithms – any_of)

Lot of work to support it for custom classes

The following members or stand-alone functions are needed:

1.Begin and end methods that operate on that structure, and that return iterators to the beginning and end of the structure.

2.The iterator itself must support:

  • an operator* method
  • an operator != method
  • an operator++ method

Pitfalls

The first one retrieves a non-const reference, allowing the developer to use the item within the vector.

The second one creates a copy. This can cause performance issues if the objects retrieved from the vector are custom and not basic types.

Relevant mentions

C++11 added the non-member functions begin and end
C++14 added cbegin, cend, rbegin, rend, crbegin, and crend.

 

QUIZ – What will happen when using the following code?

1.Compiles, but NOK. Temporary objects will be created, items in the map will not be affected.
2.Compilation error (reference of type …& cannot be initialized with a value of type …). That’s because the items within a map are of type pair<Key,Value>, and the key is const, so either we have to declare the key const, or the entire pair retrieved. (see point 3 and 4)
3.OK. Items are read only
4.OK. Items are modifiable

Leave a comment

Your email address will not be published.