Last active
November 8, 2016 18:38
-
-
Save dhruvbird/8895a6760ada80e3400a7bc6ad7bfc42 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
// Counts numbers from 0 to n-1. | |
struct Counter { | |
int i = 0; | |
int n; | |
bool first = true; // Tracks if this is the first invocation of the next() function | |
Counter(int _n): n(_n) {} | |
int* next() { | |
if (i == n) return nullptr; | |
if (!first) goto cx; | |
first = false; | |
while (i < n) { | |
return &i; // yield the next value in the sequence | |
cx: // We continue from here on the next invocation of this function | |
++i; | |
} | |
return nullptr; | |
} | |
}; | |
int main() { | |
Counter c(10); | |
int *n = c.next(); | |
while (n) { | |
cout << *n << ", "; | |
n = c.next(); | |
} | |
cout << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment