Why is the vector not updated in the loop?

I want to update the 'v' vector so that I can iterate from count 0-100.

I know this is forbidden, but what if I want to do this only? Is there any way?

int main() { // your code goes here vector<int> v; v.push_back(1); int count = 0; for(int elem: v){ if(count<100) v.push_back(count); count++; } for(int elem: v) cout << elem << endl; return 0; } 

Conclusion:

 1 0 
+5
source share
5 answers

As you can see from the range-based loop definition, end_expr is not updated between iterations. Therefore, you have only one iteration. push_back invalidates v.end() (this is what end_expr matches the description on the linked page), so you have undefined behavior.

Perhaps the easiest way to populate vector 0..100 is:

 vector<int> v(101); std::iota(v.begin(), v.end(), 0); 
+11
source

You should use this code instead

 int count = 0; while (v.size() < 100) { v.push_back(count++) } 

Changing a vector when repeating through it is not allowed

+3
source

using your code:

 for(int elem: v){ if(count<100) v.push_back(count); count++; } 

looks like this:

 int i = v.size(); for(int j = 0; j < i; j++){ v.push_back(j); } 

I do not know why ... v.size () can be stored in memory for optimization and data protection

Edit after OP comment:

try it

 int i = v.size(); for(int j = 0; j < i; j++){ if(j<100) i = v.size(); v.push_back(count); } 
+2
source

The best effective way for this operation

 vector<int> v; v.resize(100); for(unsigned int i = 0; i < v.size(); i++) { v[i] = i; } 

as mentioned above.

+2
source

A range based on a loop creates code similar to this:

 { auto && __range = range_expression ; for (auto __begin = begin_expr,__end = end_expr; __begin != __end; ++__begin) { range_declaration = *__begin; loop_statement } } 

As you can see, the range will not be updated as your container is reused.

In addition, you will most likely end up with undefined behavior, because since you drop the values ​​in vector these iterators will be invalid if you resize.

See @ user2079303 for a better way to populate your vector .

+2
source

Source: https://habr.com/ru/post/1205709/


All Articles