I have problem trying to make for each loop in C++. I'm not certain is this is possible in C++ if it is I still dont know to make it.
I have one simple problem written in pascal that does finding of the day in year when it is a friday 13 or saturday 25 no metter which day.
In pascal I have code like this:
{First I declare types}
type
months = (January, February, March, April, May, June, July, August, September, October, November, December);
...
{Then I declare variable for months}
var
m: mesec;
...
{Then I can declare for loop that will loop over months}
for m:= januar to december do
...
The similar way of doing a for each loop over enumerations is possible in python too. My question is:
Is there any way of doing for or even while loop over enumerations in C++?
I know this may seem as a beginers question but I tried on few different ways to do it doesnt work. Doesnt compile.
You could do following in c++ provided the enum values are consecutive
enum Months
{
January,
February,
// etc...
December,
Last
};
for (int month = January; month != Last; ++month)
{
// do stuff
}
No, you can't do this directly in C++. There are a few workarounds, though.
ints, and increase the cycle variable by 1 each time until it equals the last enum's value. This is described in this SO question.If the values are not increasing by 1 (e.g. enum E {FIRST = 5, SECOND = 10}, it becomes more tricky. You could make an array holding all possible values and use it (that's a crappy solution, but it works):
enum E
{
FIVE = 5,
TEN = 10,
THREE = 3
};
E arr[3] = {FIVE,TEN,THREE};
E iterator;
for( int i = 0; i < 3; i++ )
{
iterator = arr[i];
//do something with it
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With