I am learning C++ and currently trying to make an enum
type called weekday
representing the days of the week, along with some basic functions to move back and forth among the days. The enum
type is defined as so:
enum weekday {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
};
I want to make a function called changeDay
that will find the day that is delta
days away from a given startDay
. (e.g. changeDay(Monday, 4) == Friday
). I have the function defined as so:
void incrementDay(weekday& startDay, int delta){
startDay = weekday((startDay + delta) % 7);
}
This function works great as long as I'm going forwards in time (i.e. delta > 0
). However, I also want to be able to support going back in time (i.e. delta < 0
). This leads to the following problem: if I want to go, for example, 4 days prior to Tuesday, I would expect to get Friday. However, the way my function works, the value -3
would be returned, which is not defined as a valid value in my weekday
enum.
I would try manipulating the value from my changeDay
function to always return a positive value by just adding in the cardinality of the enum (7 + -3 = 4 = Friday), but it appears that "there's not really a good way to do this". (Yes, I know that I could just hard-code the number of days in the week in the function, but I'm not interested in that kind of solution).
Is there any way to essentially allow my function to loop backwards through my enum?
答案 0 :(得分:0)
Try the following
#include <iostream>
enum weekday
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
};
const char * weekday_name[] =
{
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
};
void incrementDay( weekday &startDay, int delta )
{
if ( delta )
{
delta %= Sunday + 1;
if ( delta < 0 ) delta = Sunday + delta + 1;
startDay = static_cast<weekday>( ( startDay + delta ) % ( Sunday + 1 ) );
}
}
int main()
{
for ( int i = 0; i < 14; i++ )
{
weekday day = Monday;
incrementDay( day, i );
std::cout << day << ": " << weekday_name[day] << std::endl;
}
std::cout << std::endl;
for ( int i = 0; i < 14; i++ )
{
weekday day = Monday;
incrementDay( day, -i );
std::cout << day << ": " << weekday_name[day] << std::endl;
}
}
The program output is
0: Monday
1: Tuesday
2: Wednesday
3: Thursday
4: Friday
5: Saturday
6: Sunday
0: Monday
1: Tuesday
2: Wednesday
3: Thursday
4: Friday
5: Saturday
6: Sunday
0: Monday
6: Sunday
5: Saturday
4: Friday
3: Thursday
2: Wednesday
1: Tuesday
0: Monday
6: Sunday
5: Saturday
4: Friday
3: Thursday
2: Wednesday
1: Tuesday