Is this a smart way to use loop based ranges?

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; } 
+4
source share
1 answer

The question is not about auto for-loop , but if it is reasonable to implement a foreign type of iterators. Although there are angular cases, you can make a good argument for implementing some operations as iterators (e.g. memoized fibonacci is a good example).

There are whole libraries dedicated to turning iterators into something more, so some other people also think this is a good idea.

Aside: implementing an iterator is a complex business, so methods like this should be used with caution. Boost.Iterator is a good set of helpers that can make this easier.

+3
source

Source: https://habr.com/ru/post/1447011/


All Articles