Best way to compare two int arrays of the same length?

前端 未结 4 909
日久生厌
日久生厌 2020-12-09 19:45

what is the best way to compare int arrays b and c with a:

int a[] = {0,1,0,0,1};
int b[] = {0,1,0,0,1};
int c[] = {1,1,0,0,1};

b and c are

相关标签:
4条回答
  • 2020-12-09 19:56

    Use a loop and compare the individual elements one after another.

    0 讨论(0)
  • 2020-12-09 20:00

    More information is needed on the question. I can divide your question in two ways as below,

    1. Compare array contents considering order?? Ex:char a[]={a, b, c}, b[]={a, c, b} here since you are considering the order, the contents are not same so a!=b

    1. compare array contents irrespective of order? Ex:char a[]={a, b, c}, b[]={a, c, b} here if you are not considering the order, the contents are same so a==b

    Solution for Question no 1: One can use memcmp for this problem. Because memcmp will compare lexicographical and return 0 or 1 or -1 as below

     #include<stdio.h>
        #include<string.h>
        int main()
        {
    
            char a[]={'a','b','c'};
            char b[]={'a','b','c'};
            int x=memcmp(a,b,sizeof(a));
            printf("%d\n",x);
    
        return 0;
        }
    ***output:0***
    
        #include<stdio.h>
        #include<string.h>
        int main()
        {
    
            char a[]={'a','c','b'};
            char b[]={'a','b','c'};
            int x=memcmp(a,b,sizeof(a));
            printf("%d\n",x);
    
        return 0;
        }
    ***output:1***
    
        #include<stdio.h>
        #include<string.h>
        int main()
        {
    
            char a[]={'a','b','c'};
            char b[]={'b','a','c'};
            int x=memcmp(a,b,sizeof(a));
            printf("%d\n",x);
    
        return 0;
        }
    ***output:-1***
    

    Solution for Question no 2: One can use memcmp for this problem, the best solution for this problem is as below

    Here, I answered for the above problem https://stackoverflow.com/a/36130812/5206646

    0 讨论(0)
  • 2020-12-09 20:12

    If you mean

    int a[] = {0,1,0,0,1};
    int b[] = {0,1,0,0,1};
    int c[] = {1,1,0,0,1};
    

    then

    memcmp(a, b, sizeof(a)); /* returns zero for a match */
    memcmp(a, c, sizeof(a)); /* returns nonzero for no match */
    
    0 讨论(0)
  • 2020-12-09 20:15

    Use the standard memcmp function from <string.h>.

    memcmp(a, b, sizeof(a)) == 0
    

    whenever a and b are equal.

    0 讨论(0)
提交回复
热议问题