Use indexOf() on an int-array instead of a string

Is there a way to use indexOf on an int-array instead of a string? I have an int array of hours (non-regular) at which I want to perform an action.

int hourReset[]={0,6,12,20};


if(hourReset.indexOf(Time.hour()) > -1 && Time.hour() != lastReset){
        lastReset = Time.hour();
        Particle.publish("I MUST SLEEP!");
        System.sleep(SLEEP_MODE_DEEP, 15);
   }

Sorry. In C/C++ the int is a simple built-in type and not a class. Therefore there are no methods that you can call on an instance. You will have to traverse the array the hard way to find your index.

1 Like

Sad. But thanks for the quick reply.

@eric.spaeth, here is a simple solution from StackOverflow:

First its important that the argument list contain size information for the array, i.e. passing a pointer to an array only does not provide enough information to know how many elements the array has. The argument decays into a pointer type with no size information to the function.

So given that, you could do something like this:

int findIndex(int *array, size_t size, int target) 
{
    int i=0;
    while((i<size) && (array[i] != target)) i++;

    return (i<size) ? (i) : (-1);
}

For small arrays this approach will be fine. For very large arrays, some sorting and a binary search would improve performance

2 Likes