bsearch结构中的多个项目

时间:2012-03-09 13:07:53

标签: c struct binary-search bsearch

固定。

包括

main()
{
    int n;
    int i;
    char tempMonth[255]; //Used to store the month until checked

    scanf("%d", &n);

    struct date *list;

    list = (struct date *)malloc((n * sizeof(struct date)));

    for(i = 0; i < n; i++)
    {
        scanf("%s %d %d", tempMonth, &list[i].day, &list[i].year);
        list[i].month = getMonth(tempMonth);
    }

    convertFullYear(list, n);

    qsort(list, n, sizeof(struct date), (compfn)sortDates);

    convertSmallYear(list, n);

    for(i = 0; i < n; i++)
    {
        printf("%s %d %02d\n", months[list[i].month], list[i].day, list[i].year);
    }

    char *pos = (char*) bsearch(Jan, list, sizeof(list), sizeof(Jan), findJan);
}

正如你所看到的,我已经把我认为正确的事情称为bsearch,但是如果它是正确的我不知道从哪里开始。

1 个答案:

答案 0 :(得分:1)

如果您要搜索特定日期,请使用struct date作为密钥:

struct date Jan;
Jan.month = 0;
Jan.year = 00;
Jan.day = 1;

然后您可以使用sortDates功能(您应该将其重命名为compareDates):

struct date* pos = bsearch(
    &Jan, /* pointer to the structure above */
    list, /* pointer to your array */
    n, /* number of elements in your array */
    sizeof(struct date), /* size of each element */
    (compfn)sortDates /* compare function */
);

有关更多示例,另请参阅http://www.cplusplus.com/reference/clibrary/cstdlib/bsearch/http://en.cppreference.com/w/cpp/algorithm/bsearch