在我的程序中,我有以下代码,不知何故它编译了,但它不应该。
#include <list>
#include <iostream>
int main(int argc, char* argv[])
{
std::list<int> collection = { 1, 2, 3, 4, 5, 6 };
for each (auto i in collection)
{
std::cout << i;
}
return 0;
}
我从自动完成中得到了这个代码:
for each (auto item in collection)
我在Developer Powershell中使用以下命令编译我的代码:
cl /EHsc /std:c++17 .programm.cpp
请帮帮我。我不知道为什么会发生这种情况,当我试图在互联网上搜索它时,我发现的都是无法编译的问题。
for each
循环是c++语言的microsoft特有扩展:
for each
,in
遍历数组或集合。这个非标准关键字在c++/CLI和本地c++项目中都可用。然而,不建议使用它。考虑使用标准的基于范围的for语句(c++)。
…
语法for each ( type identifier in expression ) { statements }
这就是代码在Visual Studio中编译的原因。在其他c++编译器中无法编译。