0

Problem with my code it’s crashing if the index less than the reminder of the days left.

My code worked find if I test it with Monday and increment it by two. It returns Wednesday. But if it’s Friday and increment it by four it throws an error out of range. https://code.sololearn.com/ciK6mNroq4br/?ref=app

16th Mar 2022, 3:30 AM
Yones Mussa
9 RĂ©ponses
+ 1
I'll post a snipet of the part that I edited: if (it != daysOfTheWeek.end()) { int incrementIndex = std::stoi(increment); return daysOfTheWeek[(std::distance(daysOfTheWeek.begin(),it) + incrementIndex)%7]; }
16th Mar 2022, 2:57 PM
Dennis
Dennis - avatar
+ 1
When you add incrementIndex to the iterator, the result can be larger than the size of the vector. You'll want to % 7 the result before you access the vector. There is no need to use % 7 on the previous line then because the new one will take care of it too. Also 'it - daysOfTheWeek.begin()' can be replaced with 'std::distance( daysOfTheWeek.begin(), it )'.
16th Mar 2022, 8:50 AM
Dennis
Dennis - avatar
16th Mar 2022, 3:41 AM
Yones Mussa
0
Dennis wait i tried to do it your way it crashed my whole program
16th Mar 2022, 1:09 PM
Yones Mussa
0
Can you post your updated code? When I make the change it works fine.
16th Mar 2022, 2:45 PM
Dennis
Dennis - avatar
0
Dennis so with yours if you test Friday and 4 the Result tuesday?
16th Mar 2022, 2:54 PM
Yones Mussa
0
Yes
16th Mar 2022, 2:56 PM
Dennis
Dennis - avatar
0
Dennis i did what you said exactly. Can j see your version cause mine would be a hustle to upload to here
16th Mar 2022, 2:56 PM
Yones Mussa
0
Dennis i see my mistake.
16th Mar 2022, 3:04 PM
Yones Mussa