bsearch en múltiples artículos en estructura
-
10-12-2019 - |
Pregunta
fijo.
incluye
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);
}
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);
}
Como puede ver, he puesto lo que creo que es correcto llamar Bsearch, sin embargo, si es correcto, no estoy seguro de dónde ir desde aquí.
Solución
If you're searching for a specific date, then use a struct date
as a key:
struct date Jan;
Jan.month = 0;
Jan.year = 00;
Jan.day = 1;
Then you can use your sortDates
function (you should rename it to 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 */
);
See also http://www.cplusplus.com/reference/clibrary/cstdlib/bsearch/ and http://en.cppreference.com/w/cpp/algorithm/bsearch for further examples.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow