3

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?

JohnG
  • 2,109
  • 3
  • 16
  • 12
  • are you trying to compile c# code in c++? – Gene Bushuyev Jan 21 '11 at 23:23
  • 3
    @Everyone- This is a special macro that's provided in Stanford's introductory programming courses CS106B and CS106X. We also provide a custom `Map` class that's easier to use than the STL `map`; hence the capitalization. – templatetypedef Jan 21 '11 at 23:27
  • 2
    @templatetypedef - thanks for clarification. In that case this question seems way too localized since it's so curriculum specific. – wkl Jan 21 '11 at 23:29
  • 1
    You have to question the wisdom of synthesising a construct that does not exist in a language without making it very clear to the student that they are not learning C++, but some construct invented for teaching programming in a more abstract sense. Also since the construct appears to be copied directly from C#, what is wrong with using C# for this course? – Clifford Jan 21 '11 at 23:42

5 Answers5

9

foreach is 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 using foreach and just opted to go with the standard C++ enhanced for loop.

I would generally not advice using foreach going 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.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 1
    @Oli Charlesworth- There wasn't anything wrong per se with anything in C++. The main advantage was simplicity - it's much easier to focus on more advanced ideas like recursion, linked lists, graphs, and asymptotic analysis if you don't have to introduce complex iterator syntax to look at everything in a map/set/etc. The curriculum will probably soon be updated to go over STL containers at the end of the course, meaning that `foreach` will likely be "training wheels" to simplify the material. – templatetypedef Jan 21 '11 at 23:36
  • Why would you have done such an evil thing!? If you want to teach such a construct, why not use a language that supports it directly. It reminds me of the CS graduates I used to come across who, faced with having to use C in the real world, would #define { and } as BEGIN and END to make thier code a bit more Pascal-like! – Clifford Jan 21 '11 at 23:37
  • 1
    @Clifford- The point of these courses is to get students up to speed on language-agnostic concepts like recursion, data structures, inheritance, etc. rather than to produce hardcore C++ programmers. There are other courses that focus on the specifics of C++ and other programming languages. From experience this setup actually works quite well, since students usually take it upon themselves to learn the nuances of their favorite languages. I'd prefer not to get into an argument about this since I don't think anyone's going to change their mind, but you do have a very good point. – templatetypedef Jan 21 '11 at 23:40
  • 3
    C++ was an interesting choice for teaching data structures whilst trying to ignore language-specific details! – Oliver Charlesworth Jan 21 '11 at 23:50
  • 2
    @templatetypedef: I realise that, but this student does not apper to have had that made clear to *him*, and thinks that he is learning C++. I used to be a regular on a forum where similar problems occurred perennially with US students who learned C++ on the AP Computer Science programme; some of them appeared to have made it to the workplace before finding out the courseware class libraries they'd learned were unavailable outside acedemia. – Clifford Jan 21 '11 at 23:51
  • Despite my opinion on the wisdom of this practice, this answer has to get an up-vote since it exactly answers the question, and clears up John's misunderstanding. – Clifford Jan 21 '11 at 23:57
  • Thanks everyone @templatetypedef thanks for the explanation. @Clifford - cs106b makes it clear that they are using special classes they created - even if foreach.h was not explicitly mentioned, I should have guessed I had to import the class. I am eager to discover C# since it uses foreach. – JohnG Jan 22 '11 at 00:31
  • @templatetypedef How do I contact you for the source code? I don't see any feature on stackoverflow to get in touch. – JohnG Jan 22 '11 at 00:59
  • @JohnG- It's probably best to contact your SL directly and ask for the source. It should be bundled with the standard starter code, though, and so you shouldn't need to explicitly add it in anywhere. – templatetypedef Jan 22 '11 at 01:11
  • @templatetypedef I am in DIY mode :) thanks anyway. cs106b rocks! If you want some feedback from your CS online courses, drop me a line john@safer.com - I work on University Ave in PA. – JohnG Jan 23 '11 at 23:05
3

What book are you using?

foreach is not a C++ keyword, and I think the closest extension that introduces it, with that specific syntax, into the language is in Visual C++, as described in this link: http://blogs.msdn.com/b/arich/archive/2004/09/08/227139.aspx

There is for_each in <algorithm>, but its signature is very different from what you're using (which is a very Java for-each syntax).

Also I notice that you're using Map which is different from std::map?

wkl
  • 77,184
  • 16
  • 165
  • 176
2

Because the function name is for_each P.S. I thought it was a c++ question, as the tag suggested, but the syntax all wrong for C++.

Gene Bushuyev
  • 5,512
  • 20
  • 19
1

foreach doesn't exist in C++.

In the latest version of C++ which is only just released in some of the latest compilers, you can use "Range-based for-loop" .. find it on this page: http://en.wikipedia.org/wiki/C%2B%2B0x

I doubt though that your compiler supports that. So, maybe stick with a for loop for now.

Scott Langham
  • 58,735
  • 39
  • 131
  • 204
-1

Qt is support foreach, using like this:

QDir dir("Dir");
dir=QFileDialog::getExistingDirectory(0,"Select Folder: ");
QFileInfoList list = dir.entryInfoList(QDir::Dirs| QDir::Files | QDir::NoDotAndDotDot);

std::vector<std::string> names;
foreach(QFileInfo finfo, list){
    std::string str=dir.path().toStdString().c_str();
    str=str+"/";
    names.push_back(str+finfo.fileName().toStdString().c_str());
}

but, when you using #define QT_NO_KEYWORDS on header file, foreach disabled.

helloyou
  • 11
  • 1