I have used the new range-based for loop provided by C++11 standard and I came up with the following question: suppose that we iterate over a vector<>
using the range-based for
, and we add some element in the end of the vector during this iteration. Thus, when do the loop end?
For instance, see this code:
#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; }
I tested G++ 4.8 and Apple LLVM version 4.2 (clang++) with "-std=c++11" flag, and the output is (for both):
1 2 3 1 2 3 11 13
Note that the first loop terminates in the end of original vector, although we add other elements to it. It seems that the for-range loop evaluate the container end in beginning only. Is this, in fact, the correct behavior of range-for? Is it specified by the committee? Can we trust in this behavior?
Note that if we change the first loop by
for(vector<unsigned>::iterator it = test.begin(); it != test.end(); ++it)
with invalid the iterators and come up with a segmentation fault.
std::vector
,std::deque
,std::unordered_set
andstd::unorderd_map
.