In my the cs106b book we use the expression “foreach” to go through a list of words in a Map. I implemented the code and banged my head against the wall facing mysterious errors. Here’s the code:
void DisplayWordCounts(Map<int> & wordsCount) {
foreach (string word in wordsCount) {
cout << left << setw(15) << word << right << setw(5)
<< wordsCount[word] << endl;
}
}
on the line starting with “foreach” I get the following errors:
lesson4-macbeth/life.cpp:58: error: expected primary-expression before ‘word’
lesson4-macbeth/life.cpp:58: error: ‘foreach’ was not declared in this scope
lesson4-macbeth/life.cpp:58: error: expected `;’ before ‘{‘ token
I guess foreach is not recognized. In that case, how can I go through a list of items from the Map class?
foreachis not a standard C++ feature. This was something Eric Roberts and I developed for the Stanford introductory programming sequence and predates the more modern C++11 range-based for loop. Now that C++11 compiler support is more widespread, we’ve stopped usingforeachand just opted to go with the standard C++ enhancedforloop.I would generally not advice using
foreachgoing forward as it’s nonstandard. However, if you’re compiling older code that uses it, you’ll need to include one of the header files from the Stanford C++ Libraries that defines it.