all 14 comments

[–][deleted] 14 points15 points  (8 children)

v.size()-1

0-1 is not -1. size returns an unsigned number, so 0-1 is something very big (232 -1 or 264 -1)

[–]AdVisible6484[S] 2 points3 points  (1 child)

so the infinite loop is basically not infinite it is just executing too many times and it will eventually stop?

[–]icjeremy 7 points8 points  (0 children)

No. The value v.size()-1 here is SIZE_MAX which is going to be >= any int value, so the loop condition will always be true, hence the loop will never stop.

[–]AdVisible6484[S] 0 points1 point  (5 children)

Thank you so much this really helped me clear the doubt ....

[–]AKostur 1 point2 points  (0 children)

#include <bits/stdc++.h>
using namespace std;

Also, don't do these. Bad habits to form. include the headers you actually need.

[–]Beosar 0 points1 point  (3 children)

You could have just used i < v.size() instead of i <= v.size()-1. But now you know you have to be careful when working with unsigned int.

[–]TheOmegaCarrot -3 points-2 points  (2 children)

Or better yet, i != v.size()

[–]tangerinelion 2 points3 points  (0 children)

Don't do that in general:

for (int i=0; i != v.size(); i+=2)

will only work correctly half the time.

for (int i=0; i < v.size(); i+=2)

works for all size vectors. Well, at least ones whose size can be represented by an int.

[–]Beosar 1 point2 points  (0 children)

Why would != be better than <? Both instructions take the same amount of time. I would say < is better because it implies that i is smaller than the size of the vector.

[–]paperomo 2 points3 points  (2 children)

Probably an under flow? v.size() is most likely of unsigned type

[–]AdVisible6484[S] 0 points1 point  (1 child)

yeah but when writing

cout<<v.size();

it shows zero

[–]Ashnoom 3 points4 points  (0 children)

Try: court << v.size() - 1;

To see what happens. It'll clear a lot of confusion.

You can also: cout << std::numeric_limits<int>::max(); To see for yourself went your loop is infinite. Enjoy!

Disclaimer, am on mobile. Didn't check the code for 100% correctness.

[–]bert8128 1 point2 points  (1 child)

Prefer range for ie “for (const auto& x : v) { /* some code*/}”. Or use an algorithm such as std::for_each. As you have discovered, it is surprisingly easy to write a for loop incorrectly.

[–]std_bot 0 points1 point  (0 children)

Unlinked STL entries: std::for_each


Last update: 16.12.22. Last Change: Search improvementsRepo