[英]Doing binary search in an array of structures
所以我有一個名為 jogo 的結構和一個帶有 jogo 類型變量的數組。
結構:
typedef struct
{
int id;
char nome[1024];
char equipas[2][1024];
int pont[2];
} jogo;
我想要做的是二進制搜索以找到相應的名稱並在找到名稱時返回其id。
例子:
// Example of elements inside the array
jogo array[3] = {{0,ElClassico1,Barcelona,RealMadrid,2,0},
{1,ElClassico2,Barcelona,RealMadrid,1,3},
{2,ElClassico3,Barcelona,RealMadrid,3,4}}
因此,例如,如果我對名稱 ElClassico2 進行二進制搜索,我希望二進制搜索返回 1,它是該 jogo 的 id。
如果有人能告訴我如何做到這一點,我將不勝感激,因為我不明白如何做到這一點。
如果要使用標准庫二進制搜索,可以這樣使用:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct
{
int id;
char nome[1024];
char equipas[2][1024];
int pont[2];
} jogo;
int jogo_compare_nome(void const *a, void const *b)
{
return strcmp(((jogo*)a)->nome, ((jogo*)b)->nome);
}
int main(void)
{
jogo array[3] = {
{0, "ElClassico1", {"Barcelona", "RealMadrid"}, { 2, 0}},
{1, "ElClassico2", {"Barcelona", "RealMadrid"}, { 1, 3}},
{2, "ElClassico3", {"Barcelona", "RealMadrid"}, { 3, 4}},
};
jogo j1 = { .nome = "ElClassico2" };
jogo j2 = { .nome = "ElClassico7" };
jogo* p;
p = bsearch(&j1, array, 3, sizeof(jogo), jogo_compare_nome);
if (p) {
printf("Found id=%i\n", p->id);
}
else {
printf("Not found!\n");
}
p = bsearch(&j2, array, 3, sizeof(jogo), jogo_compare_nome);
if (p) {
printf("Found id=%i\n", p->id);
}
else {
printf("Not found!\n");
}
return EXIT_SUCCESS;
}
無論如何,請記住二進制搜索需要按搜索鍵排序的序列(好的,按鍵分區,但這是挑剔的)。 您可以在搜索之前使用qsort()
。
順便說一句,那些 1 KB arrays 調用動態 memory 分配(我的意見)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.