我有 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 。
- 有没有更有效的方法来保存这些“匹配项”?
- 如何尽可能高效地遍历具有输入的引脚数组并找到其匹配项?
最佳答案
如果数组引脚是有序的(否则您可以使用例如 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/