There are some cases which i'll have to loop through an array/vector looking for an element that satisfies a condition that involves the element's value.In the past i'd go for a simple for
loop together with an if
statement, but lately i saw a piece of code that seems more simple.To be precise:
I used to do it like this:
for( int i = 0; i < vector.size(); i++ )
if( condition[i] )
do_stuff;
And now im curious about this one:
int i = 0;
while( i < vector.size() || condition[i] )
i++;
I like that definition,it's shorter and in fact i believe it's easier to read,but what bothers me is the case where the vector is empty.
I'm not sure about the way ||
processes the boolean values, does it check the first condition and if it's false goes for the second one? Or does it check both nevertheless? If that's the case,there should be an error since Im checking for a condition on an element that doesn't exist.
After trying the code on an empty vector it compiled and ran just fine,just to ensure i tried this one as well:
bool a , b = false;
if( b || a )
dostuff;
And it worked just fine as well.
But it still doesn't seem completely right to me checking conditions on nonexisting values and im not sure if i should use it.Is it okay or should i go for something else?
Any help would be great.
Edit 0: Still it should throw an error since the vector is empty. 0 < 0 returns false , so the second condition will still be checked.