문제

Ok so I have an array that lists the 5 weekdays in order:

char *days[5]={"Monday","Tuesday","Wednesday","Thursday","Friday"};

Now I have some struct arrays and one of the elements are the days of the week and they are not in order, they are in random order like:

d[0].day is "Thursday"
d[1].day is "Monday"
d[2].day is "Wednesday"

Now inconveniently the days aren't in alpha order :p so that makes me wonder how I can implement a sort of some kind =/

도움이 되었습니까?

해결책

I think it's better to make the days of week by enum . Like:

enum Days{
    Monday = 1,
    Tuesday,
    Wednesday,
    Thursday,
    Friday
}

Then you get the day data by function like

void  printDays(enum d,char * buffer)
{
 const char *daysName[] = {"Monday","Tuesday","Wednesday","Thursday","Friday"};
 memcpy(buffer,daysName[d-1]);
}

Then when you use

 d[0].day is "Thursday"
d[1].day is "Monday"
d[2].day is "Wednesday"

It is easy sort .It in fact just store 1,2,3,4,5!

다른 팁

OK, to sort this properly, you need to be able to compare two structures and see which is earlier. Once you have that, you can use it for sorting with your favorite sorting algorithm.

To convert s1 and s2, you need to convert s1.day and s2.day into a number - 0 for Monday, 1 for Tuesday, etc... and then compare the numbers. Converting a day string to a number is easy - loop over your days array, and see which entry in it is identical to s1.day .

Write a function that takes a day of the week as parameter and returns an int. Return 1 for Sunday, 2 for Monday, and so on.

Then write another function that takes two days as parameters, and using the first function, return the earlier day.

Now using these two functions you can implement any standard sorting algorithm. Same as sorting numbers.

Or,

You can have another array of same size as the array containing your structure. You then copy the structure into the new array, but first copy all Sundays, then all Mondays, and so on.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top