|
|
<!-- --- title: OpenFOAM C++ Coding Patterns (HashTable) -->
|
|
|
|
|
|
[Back to _coding patterns_](/coding/patterns/patterns)
|
|
|
***We are happy to incorporate content from volunteers!!***
|
|
|
|
|
|
|
|
|
## Coding Patterns
|
|
|
|
|
|
### HashSet
|
|
|
|
|
|
Use range-for to dereference the HashSet iterators directly:
|
|
|
```
|
|
|
labelHashSet ids ...;
|
|
|
|
|
|
for (const label id : ids)
|
|
|
{
|
|
|
os << id << nl;
|
|
|
}
|
|
|
```
|
|
|
|
|
|
**Anti-pattern**: using iterators:
|
|
|
```
|
|
|
labelHashSet ids ...;
|
|
|
|
|
|
forAllConstIters(ids, iter)
|
|
|
{
|
|
|
os <<iter.key() << nl;
|
|
|
}
|
|
|
|
|
|
// Even worse - using old macros!
|
|
|
forAllConstIter(labelHashSet, ids, iter)
|
|
|
{
|
|
|
os <<iter.key() << nl;
|
|
|
}
|
|
|
```
|
|
|
|
|
|
### HashTable, Map
|
|
|
|
|
|
Use `lookup()` to provide default values (const-access) and the `operator()`
|
|
|
to create new zero-initialized entries if required:
|
|
|
```
|
|
|
Map<label> counter;
|
|
|
...
|
|
|
|
|
|
os << "hits: " << counter.lookup(i, 0) << nl;
|
|
|
|
|
|
++counter(j);
|
|
|
```
|
|
|
|
|
|
**Anti-pattern**: the manual equivalents:
|
|
|
```
|
|
|
Map<label> counter;
|
|
|
...
|
|
|
|
|
|
os << "hits: " << (counter.found(i) ? *(counter.cfind(i)) : 0) << nl;
|
|
|
|
|
|
|
|
|
Map<label>::iterator iter = counter.find(j);
|
|
|
|
|
|
if (!iter.found())
|
|
|
{
|
|
|
counter.insert(j, 0);
|
|
|
}
|
|
|
else
|
|
|
{
|
|
|
++(*iter);
|
|
|
}
|
|
|
```
|
|
|
|
|
|
----
|
|
|
|
|
|
Copyright (C) 2019 OpenCFD Ltd. |