for each 和 for_each 和有什么不一样?

What is the difference between for each and for_each?

我接手了一段旧代码,需要使用JNI调用。在代码中看到了for each( in )的用法,但是这段代码在Linux.

下无法编译

我很想知道for each是怎么生成的,可以使用哪些平台,在Linux下编译的时候有没有?

我正在尝试理解for each的语法,但是这些信息几乎是不可能找到的,但是有很多for_each的用法。

在Windows平台上,我只用Visual Studio 2013 (v120)编译成功,v14之后的版本异常。

在Linux平台下,我用下面的命令编译,报了很多错。结果如下:

g++ -I/usr/java/jdk1.8.0_191/include/ -I/usr/java/jdk1.8.0_191/include/linux/ -fPIC -shared -o ErmjJNI.so *.cpp -pthread -std=c++11

ErmjAI.cpp: In member function ‘virtual void ErmjAI::initGame(size_t, size_t, const std::vector<std::vector<int> >&, std::string, std::string)’:
ErmjAI.cpp:74:8: error: expected ‘(’ before ‘each’
    for each (size_t tile in tiles[i])
        ^
ErmjAI.cpp:74:21: error: expected primary-expression before ‘tile’
    for each (size_t tile in tiles[i])
                     ^
ErmjAI.cpp:74:37: error: ‘each’ was not declared in this scope
    for each (size_t tile in tiles[i])
                                     ^
ErmjAI.cpp:75:4: error: expected ‘;’ before ‘{’ token
    {
    ^
ErmjAI.cpp:3346:1: error: expected primary-expression at end of input
 }

我在这个(http://www.cplusplus.com/search.do?q=for+each)网站上查询了相关的API,但是没有任何收获。

这样的代码太多了,我已经快没耐心了,下面举几个例子。

for each (size_t tile in tiles[i])
{
    if (tile<=33)
    {
        tNum[tile]++;
        _unseen_tiles_num[tile]--;
    }
    else
    {
        m_vecHua[i].push_back(tile);
    }
}
for each (size_t tile in tiles[i])

不像C++,改成:

for (size_t tile : tiles[i])

您还可以read基于范围的 for 在 C++ 中的工作原理。

for each, in is a non-standard syntax in the Microsoft compiler that even they don't recommend using. I suggest you change the code to use a C++11 ranged-based for 循环。这将得到符合标准的编译器的支持。

for (size_t tile : tiles[i])
{
    // your code
}