从C ++ 11开始,我们可以写:
vector<int> v{1, 2, 3, 4};
for (auto x : v)
{
cout << x << endl;
}
根据Essentials of Modern C++ Style,以下代码很快在C ++中也是合法的:
vector<int> v{1, 2, 3, 4};
for (x : v)
{
cout << x << endl;
}
此功能是否可在C ++ 17或C ++ 20中使用?
答案 0 :(得分:58)
没有。这被委员会more than two years ago杀死,主要是因为担心由影子引起的混淆:
std::vector<int> v = { 1, 2, 3, 4 };
int x = 0;
for(x : v) {} // this declares a new x, and doesn't use x from the line above
assert(x == 0); // holds
反对意见在这个过程中发生得如此晚,以至于Clang和GCC在整个委员会被拒绝时已经实施了该功能。这些实现最终被撤消:Clang GCC
答案 1 :(得分:4)
这仍然是an open issue。在那里有一个提案,将其添加到C ++ 17中。 That proposal was rejected。是否接受新提案取决于提案,因此现在判断C ++ 20是否可能拥有它还为时尚早。
答案 2 :(得分:1)
<强>更新强>
GCC 5.1允许使用-std = c ++ 1z的语法。
自GCC 6.1以来不再允许这样做。所以这个答案看起来并不正确。
Ideone编译器在C ++ 14下成功编译了这样的代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v {1, 2, 3, 4};
for (x : v)
cout << x << endl;
return 0;
}