Recently, I was interested to know what the requirements were for ranges based on loops in C ++ 11, since I saw only examples of the intended use:
for (auto person : people) { cout << person.name << endl; }
But, considering that the container needs only the initial and final methods, but it should not contain anything at all, can it be considered that the following is considered "bad practice"? If nothing else, this is a new 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; }
source share