Skip to content

Instantly share code, notes, and snippets.

@dhruvbird
Last active November 8, 2016 18:38
Show Gist options
  • Save dhruvbird/8895a6760ada80e3400a7bc6ad7bfc42 to your computer and use it in GitHub Desktop.
Save dhruvbird/8895a6760ada80e3400a7bc6ad7bfc42 to your computer and use it in GitHub Desktop.
#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