I have not seen a single canonical cycle.
The cost of creating an iterator is indicated as O(1) (based on the size of the container), but it can be worth it, especially if certain debugging options are activated.
Therefore, calling end at each iteration of the loop is wasteful.
Thus, the canonical way of writing a for loop is to compute both it and end in the first statement.
typedef std::map<int,int> LayoutType; for (LayoutType::const_iterator it = layout.begin(), end = layout.end(); it != end; ++it) {
I usually type in my container, but honestly, it makes no sense to specify an iterator, it is already available in the container and introduces too many synonyms, it does not help.
It could also be a personal quirk, but I prefer to specify a function rather than a type when I enter my typedef. The type may change during subsequent refactoring, the function will not (at least it will not be the same if it happens, so it will require a complete rewrite).
For example, what if you suddenly prefer: typedef std::unordered_map<int,int> LayoutType ? It still fits your needs, and you can possibly opt out of it without any rewriting costs (assuming you used a typedef).
Matthieu M.
source share