Re: irregular (non-consecutive) iteration (for loop)
Nobody wrote:
suppose I want to iterate for a specific variable e.g. i , but for non
regular (or consecutive) values. For example i=0,1,2,4,5,7,8 etc
how can I do that with a for loop?
MY solution which is not that elegant involves if statements (or switch
statements) in the body of the loop: e.g.
is there a more elegant/compact/precise way of doing the above?
You could overload all necessary operators of a "Range" class
that has an underlying vector (or sth. else). If so, you might
write:
int main()
{
int irregular[] = {1,2,2,2,5};
Range i(irregular, 5); // <== that's our class
for(i=0; i<5; i++) // looks ok ...
cout << i << endl;
return 0;
}
This would indeed show the sequence given in the
int array 'irregular'.
How would such a range class look like? Simple, just
inherit from a std::vector and add the overloads:
class Range : public vector<int>{
int pos;
public: Range(int a[], int n) : vector<int>(a, a+n), pos(0) {}
int operator ++ (int) { return operator[](pos++); }
int operator = (int v) { return pos = v; }
int operator < (int b) { return pos < b; }
int operator () () const { return operator[](pos); }
operator int() const { return operator[](pos); }
};
Of course, to get that working you'll
need the headers:
#include <vector>
#include <iostream>
and you would add here:
using namespace std;
before the class definition.
Regards
Mirco