Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index of first non zero value in a vector<int> in c++

Tags:

c++

c++11

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

like image 246
Gunjan Avatar asked Dec 08 '22 00:12

Gunjan


1 Answers

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.

like image 88
M.M Avatar answered Feb 23 '23 14:02

M.M