Check if a value exists in an array in Cython

后端 未结 2 1072
旧巷少年郎
旧巷少年郎 2020-12-02 01:56

I want to know how to check if a value or a object exists in an array, like in python:

a = [1,2,3,4,5]
b = 4
if b in a:
    print(\"True!\")
else:
    print(         


        
相关标签:
2条回答
  • 2020-12-02 02:03

    You pretty much have to iterate through the array and check each element.

    #include <stdbool.h>
    
    bool isvalueinarray(int val, int *arr, int size){
        int i;
        for (i=0; i < size; i++) {
            if (arr[i] == val)
                return true;
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-12-02 02:16

    Try next:

    (read comments and tests for details how it working)

    #include <stdio.h>
    #include <assert.h>
    
    
    /*
    Return index an integer number begin from start an array,
    otherwise return -1.
     */
    int indexOf(int *array, int array_size, int number) {
        for (int i = 0; i < array_size; ++i) {
            if (array[i] == number) {
                return i;
            }
        }
        return -1;
    }
    
    
    // Tests for indexOf()
    void test_indexOf() {
        int array[10] = {12, 78, -43, 0, 21, 12, 20, -9, 1, -1};
        assert(indexOf(array, 10, 12) == 0);
        assert(indexOf(array, 10, 0) == 3);
        assert(indexOf(array, 10, 2) == -1);
        assert(indexOf(array, 10, 43) == -1);
        assert(indexOf(array, 10, 11) == -1);
        assert(indexOf(array, 10, -1) == 9);
        assert(indexOf(array, 10, 1) == 8);
        assert(indexOf(array, 10, -2) == -1);
        assert(indexOf(array, 10, 3) == -1);
    }
    
    
    int main () {
        test_indexOf();
        return 0;
    }
    

    Notes:

    1. Since the C has not support for reload functions, indexOf() will be work only with array type of integer.

    2. The C has not support for determinate length of a pointer of an array. So, you need manually pass size of array.

    3. Testing environment:

    -

    $ uname -a
    Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
    $ gcc --version
    gcc (Ubuntu 4.8.5-2ubuntu1~14.04.1) 4.8.5
    
    0 讨论(0)
提交回复
热议问题