I was wondering recently what the requirements were for range based for loops in c++11, as I had only ever seen examples of intended usage:
for (auto person : people)
{
cout << person.name << endl;
}
But given that a container need only have begin and end methods, but need not contain anything at all, would the below be considered ‘bad practice’ in any way? If nothing else, it is a fresh answer if someone asks you for a Fibonacci sequence in an interview!
#include <string>
#include <iostream>
#include <Windows.h>
using namespace std;
struct FibItr
{
FibItr(int cur = 1, int prev = 0) : mCur(cur), mPrev(prev) {}
FibItr & operator++()
{
mCur += mPrev;
mPrev = mCur - mPrev;
return *this;
}
int operator*(){ return mCur; }
bool operator!=(const FibItr & _rhs)
{
return mCur != _rhs.mCur || mPrev != _rhs.mPrev;
}
unsigned int mCur, mPrev;
};
struct Fib
{
FibItr begin() { return FibItr(); }
FibItr end() { return FibItr(0, 0); }
};
int main( int argc, char* argv[] )
{
for (auto num : Fib())
{
cout << num << endl;
Sleep(500);
}
return 0;
}
The question is not really about the
auto for-loopbut if it is reasonable to implement stranger kind of iterators. While there are corner-cases you can make a perfect good argument for implementing some operations as iterators (memoized fibonacci being a good example).There are whole libraries devoted to turning iterators in something more, so some other people also think it is a good idea.
As an aside: Implementing an iterator is tricky business, which is why methods like this should be used with care. Boost.Iterator is a good set of helpers that can make that easier.