... | ... | @@ -7,11 +7,11 @@ |
|
|
|
|
|
## Coding Patterns
|
|
|
|
|
|
### HashSet
|
|
|
### HashSet iteration
|
|
|
|
|
|
\since 1706
|
|
|
|
|
|
Use range-for to dereference the HashSet iterators directly:
|
|
|
Use a _range-for_ to dereference the `HashSet` iterators directly:
|
|
|
```
|
|
|
labelHashSet ids ...;
|
|
|
|
... | ... | @@ -20,6 +20,16 @@ for (const label id : ids) |
|
|
os << id << nl;
|
|
|
}
|
|
|
```
|
|
|
Note that since `label` is a primitive we use it directly instead of
|
|
|
a reference. For a `wordHashSet` this is slightly different:
|
|
|
```
|
|
|
wordHashSet identifiers ...;
|
|
|
|
|
|
for (const word& ident : identifiers)
|
|
|
{
|
|
|
os << ident << nl;
|
|
|
}
|
|
|
```
|
|
|
|
|
|
**Anti-pattern**: using iterators:
|
|
|
```
|
... | ... | @@ -37,11 +47,46 @@ forAllConstIter(labelHashSet, ids, iter) |
|
|
}
|
|
|
```
|
|
|
|
|
|
|
|
|
### HashSet/HashTable/Map toc()
|
|
|
|
|
|
\since 1706
|
|
|
|
|
|
Use a _range-for_ when using `toc()` or `sortedToc()` to access hashes.
|
|
|
It avoids an intermediate variable, and C++ will only need to create the
|
|
|
end-iterator once.
|
|
|
|
|
|
```
|
|
|
HashTable<Type> myHash ...;
|
|
|
|
|
|
for (const word& ident : myHash.sortedToc())
|
|
|
{
|
|
|
os << ident << " = " << myHash[ident] << nl;
|
|
|
}
|
|
|
```
|
|
|
|
|
|
**Anti-pattern**: using an intermediate variable for storage:
|
|
|
```
|
|
|
HashTable<Type> myHash ...;
|
|
|
|
|
|
const wordList keys(myHash.sortedToc());
|
|
|
|
|
|
for (const word& ident : keys)
|
|
|
{
|
|
|
os << ident << " = " << myHash[ident] << nl;
|
|
|
}
|
|
|
```
|
|
|
The compiler _might_ be smart enough to eliminate the intermediate
|
|
|
variable, but the code is less clear and separating the population
|
|
|
of intermediate with its use risks potential mismatches in the future
|
|
|
when code is modified.
|
|
|
|
|
|
|
|
|
### HashTable, Map
|
|
|
|
|
|
\since 1706
|
|
|
|
|
|
Use `lookup()` to provide default values (const-access) and the `operator()`
|
|
|
Use `lookup()` to handle default values (const-access) and the `operator()`
|
|
|
to create new zero-initialized entries if required:
|
|
|
```
|
|
|
Map<label> counter;
|
... | ... | |