简体   繁体   English

mem比较数组以获得匹配字节数

[英]mem compare arrays to get number of matching bytes

int a[10];
int b[10];
memcmp(a, b, sizeof(int) * 10);

memcmp() only tells us which memory block is bigger/smaller since it just returns -1,0,+1. memcmp()只告诉我们哪个内存块更大/更小,因为它只返回-1,0,+ 1。 Is there a way to know number of matching elements in a[] and b[] just after which the mismatch occurs. 有没有办法知道a[]b[]中匹配元素的数量,之后就会发生不匹配。

Ex: a = {1, 2, 3, 4, 5, 6}
    b = {1, 2, 4}

Here memcmp(a, b, sizeof(int)* 3) would return -1. 这里memcmp(a, b, sizeof(int)* 3)将返回-1。 I want to get 2 as answer Is there a way we can get number of matching elements with help of memcmp or some similar inbuilt function 我想得到2作为答案有没有办法我们可以借助memcmp或一些类似的内置函数获得匹配元素的数量

I assume you want a low level answer since you must have already rejected the easy way with a loop. 我假设你想要一个低级答案,因为你必须已经拒绝了循环的简单方法。

You could XOR the memory block a[0] to a[9] with b[0] to b[9]. 您可以使用b [0]到b [9]对存储器块a [0]到[9]进行异或。 The resulting memory will be a block of zeros if, and only if, the original arrays were equal. 如果且仅当原始数组相等时,生成的内存将是一个零块。 To get the number of matching elements, count the number of int blocks that have all zero bits. 要获取匹配元素的数量,请计算具有全零位的int块的数量。

You could do this blisteringly fast in assembler as the operations are so simple. 由于操作非常简单,您可以在汇编程序中快速执行此操作。

A for loop over the two arrays should suffice: 两个数组上的for循环应该足够了:

int a[10];
int b[10];
int aLen = sizeof(a)/sizeof(int); /* we can do this since arrays are declared on the stack */
int bLen = sizeof(b)/sizeof(int);
int currentContig = 0;
int maxContig = 0;

for (int aIdx = 0, int bIdx = 0; (aIdx < aLen) && (bIdx < bLen); ) {
    if (a[aIdx] == b[bIdx]) {
        currentContig++;
        aIdx++;
        bIdx++;
    }
    else if (a[aIdx] > b[bIdx]) {
        currentContig = 0;
        aIdx++;
    }
    else {
        currentContig = 0;
        bIdx++;
    }
    if (currentContig > maxContig) {
        maxContig = currentContig;
    }
}

fprintf(stdout, "longest contiguous match: %d\n", maxContig);

Please Try Like below 请尝试如下

int matched_num=0;
while(a[matched_num]==b[matched_num])
matched_num++;
printf("%d",matched_num);

final printed value will be total number of matched element in both arrays. 最终打印值将是两个数组中匹配元素的总数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM