繁体   English   中英

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

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

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

memcmp()只告诉我们哪个内存块更大/更小,因为它只返回-1,0,+ 1。 有没有办法知道a[]b[]中匹配元素的数量,之后就会发生不匹配。

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

这里memcmp(a, b, sizeof(int)* 3)将返回-1。 我想得到2作为答案有没有办法我们可以借助memcmp或一些类似的内置函数获得匹配元素的数量

我假设你想要一个低级答案,因为你必须已经拒绝了循环的简单方法。

您可以使用b [0]到b [9]对存储器块a [0]到[9]进行异或。 如果且仅当原始数组相等时,生成的内存将是一个零块。 要获取匹配元素的数量,请计算具有全零位的int块的数量。

由于操作非常简单,您可以在汇编程序中快速执行此操作。

两个数组上的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);

请尝试如下

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

最终打印值将是两个数组中匹配元素的总数。

暂无
暂无

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

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