foreach not recognized in C++

前端 未结 9 1270
离开以前
离开以前 2021-01-21 08:07

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 erro

相关标签:
9条回答
  • 2021-01-21 08:20

    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.

    0 讨论(0)
  • 2021-01-21 08:24

    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++.

    0 讨论(0)
  • 2021-01-21 08:27

    The code in your example looks like a mix of C# and C++ syntax. The foreach construct itself is C# syntax, C++/CLI (supported by VC++) has a for each construct as does C++0x (supported by GCC 4.6), but neither followw that syntax.

    0 讨论(0)
  • 2021-01-21 08:30

    I suggest for_each.

    0 讨论(0)
  • 2021-01-21 08:36

    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.

    0 讨论(0)
  • 2021-01-21 08:37

    Try iterating through the size of the map.

    for(int i=0;i<MAP.size();++i)
        // something with MAP.at(i);
    

    Replace MAP with your map object.

    Good luck!

    Regards,
    Dennis M.

    0 讨论(0)
提交回复
热议问题