What is the best way to do this.
For eg. I have
Vector<int> temp = {0,0,1,0,2}
I want to get the index of first non-zero value in the temp. So in this case I want answer 2.
I am already doing this, looking for a better way..
int index = -1;
for(int round=0; round < temp.size(); round++)
{
if(temp[round] > 0)
{
index = round;
break;
}
}
Thanks, Gunjan
You can use:
distance( begin(temp), find_if( begin(temp), end(temp), [](auto x) { return x != 0; }));
This will return the size of the array if the item is not found. You will need #include <algorithm>
and C++14 compilation mode. In C++11 you must replace auto
with int
or whatever type your container contains.
Here is a version with re-usable lambda, maybe slightly easier to read. Requires C++14.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With