c - 匹配两个数组的有效方法

标签 c arrays search binary-search

我有 2 个数组,一个是输入 pin names,另一个是它们的 actual numbers

const char *pins[]={"d1","d2","d3","d4","d5","o1","o2","o3","o4"};
const int pinsNumbers[9]={1,2,19,4,14,6,12,15,17};

当我得到输入 "d3" 时,我想找到对应的 - 19

  1. 有没有更有效的方法来保存这些“匹配项”?
  2. 如何尽可能高效地遍历具有输入的引脚数组并找到其匹配项?

最佳答案

如果数组引脚是有序的(否则您可以使用例如 qsort 对其进行排序),那么您可以使用演示程序中显示的以下方法

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int cmp( const void *a, const void *b )
{
    const char *lhs = *( const char ** )a;
    const char *rhs = *( const char ** )b;

    return strcmp( lhs, rhs );
}

int main( void ) 
{
    const char *pins[]      = { "d1", "d2", "d3", "d4", "d5", "o1", "o2", "o3", "o4" };
    const int pinsNumbers[] = { 1, 2, 19, 4, 14, 6, 12, 15, 17 };

    const char *key = "d3";

    const char **p = bsearch( &key, pins, sizeof( pins ) / sizeof( *pins ), sizeof( const char * ), cmp );

    if ( p ) printf( "%d\n", pinsNumbers[p - pins] );

    return 0;
}

程序输出为

19

关于c - 匹配两个数组的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38635601/

相关文章:

ios - NSMutableArray 实例是否在 SWIFT 中默认为 optional ?

python - 查找最不常出现的模糊字符串

php - 在 PHP 中,在数组中搜索包含子字符串的值的快速方法是什么?

c - 如何比较表格

arrays - 这是 DBSCAN 算法的预期行为吗(两个相同的数据样本不适契约(Contract)一个集群)?

c - 如何在c中的数组中插入多个元素

php - 在 PHP 中应该使用数组还是类来保存多个变量?

algorithm - 搜索树状结构化关系数据的算法(使用示例:elasticsearch)

c++ - 文件*作为公众

在 C 中创建和显示基本 BST