foreach.hforeach keyword, which implements
a substitute for the range-based for loop from C++11.
All iterable classes in the Stanford libraries import this file, so
clients don't ordinarily need to do so explicitly. This version of
foreach also supports C++ strings and arrays.
| Statement | |
The foreach statement steps through the elements in a collection. | |
foreach (type var in collection) { ... }
foreach statement steps through the elements in
a collection. It works correctly with the collection classes in
both the Standard Template Library and the Stanford C++ libraries,
but can also be used with C++ strings and statically initialized
arrays.
The following code, for example, prints every element in the
string vector lines:
foreach (string str in lines) {
cout << str << endl;
}
Similarly, the following function calculates the sum of the character
codes in a string:
int sumCharacterCodes(string str) {
int sum = 0;
foreach (char ch in str) sum += ch;
return sum;
}
As a simplification when iterating over maps, the foreach
macro iterates through the keys rather than the key/value pairs.