匹配两个数组的有效方法

时间:2016-07-28 11:53:33

标签: c arrays search binary-search

我有2个数组,一个是输入pins 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. 如何使用输入在引脚阵列上循环并尽可能有效地找到匹配?

4 个答案:

答案 0 :(得分:4)

如果数组引脚是有序的(否则您可以使用例如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

答案 1 :(得分:3)

您可以像这样构建数据以模拟C ++地图:

struct My_pair {
    const char* pin;
    int number;
};

const My_pair pairs[] = {
    {"d1", 1},
    {"d2", 2},
    ...
};

答案 2 :(得分:2)

尽可能简单快捷。如果您将使用两个连续符号(例如'a''b') - 您可以计算并检查它,就像代码中的组内偏移一样。 Ideone online executable code.

#include <stdio.h>

#define D1_VAL  1
#define D2_VAL  2
#define D3_VAL  19
#define D4_VAL  4
#define D5_VAL  14

#define D_CNT   5
#define D_OFS   0

#define O1_VAL  6
#define O2_VAL  12
#define O3_VAL  15
#define O4_VAL  17

#define O_CNT   4
#define O_OFS   D_CNT

#define PIN_NUM_CNT     (D_CNT+O_CNT)
#define PIN_GRP_CNT     2

enum decode_res_e {
    DECODE_OK = 0,
    DECODE_ERR = !DECODE_OK
};

int const pin_num_tab[PIN_NUM_CNT] = {
    D1_VAL, D2_VAL, D3_VAL, D4_VAL, D5_VAL,
    O1_VAL, O2_VAL, O3_VAL, O4_VAL,
};

typedef struct { unsigned char chr, ofs, cnt; } pin_grp_t;

pin_grp_t const pin_grp_tab[2] = {
    { .chr = 'd', .ofs = D_OFS, .cnt = D_CNT },
    { .chr = 'o', .ofs = O_OFS, .cnt = O_CNT },
};

int pin_to_num(int * num, unsigned char * pin)
{
    unsigned char i = 0, tmp = pin[1] - 0x31;
    while (i < PIN_GRP_CNT) {
        if (pin_grp_tab[i].chr == pin[0]) {
            if (tmp >= pin_grp_tab[i].cnt) break;
            *num = pin_num_tab[pin_grp_tab[i].ofs + tmp];
            return DECODE_OK;
        }
        i++;
    }
    return DECODE_ERR;
}

int main(void) 
{
    int num;
    unsigned char const inp[] = "d3";
    printf("\f%s is ",inp);
    if (pin_to_num(&num,inp) == DECODE_OK) {
        printf("%d\r\n",num);
    } else {
        printf("err\r\n");
    }
    return 0;
}

答案 3 :(得分:1)

只要上面的数组已排序,您就可以使用binary search ....