我使用了C ++ 11标准提供的新的基于范围的for循环,我提出了以下问题:假设我们迭代了 vector<>
使用基于范围的 for
,在迭代过程中,我们在向量的末尾添加了一些元素。那么,什么时候循环结束?
例如,请参阅以下代码:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<unsigned> test({1,2,3});
for(auto &num : test) {
cout << num << " ";
if(num % 2)
test.push_back(num + 10);
}
cout << "\n";
for(auto &num : test)
cout << num << " ";
return 0;
}
我用“-std = c ++ 11”标志测试了G ++ 4.8和Apple LLVM版本4.2(clang ++),输出是(对于两者):
1 2 3
1 2 3 11 13
请注意,第一个循环终止于原始向量的末尾,尽管我们添加了其他元素。似乎for-range循环仅在开始时评估容器结束。 事实上,这是范围的正确行为吗?它是由委员会指定的吗?我们能相信这种行为吗?
请注意,如果我们改变第一个循环
for(vector<unsigned>::iterator it = test.begin(); it != test.end(); ++it)
使迭代器无效并出现分段错误。