Skip to content

Instantly share code, notes, and snippets.

@ony
Last active August 29, 2015 14:16
Show Gist options
  • Save ony/40d447f9a17c2a623e30 to your computer and use it in GitHub Desktop.
Save ony/40d447f9a17c2a623e30 to your computer and use it in GitHub Desktop.
Multiple iterators over single container
#include <cstdio>
using namespace std;
struct range
{
int a, b;
struct n_iter
{
int x;
int operator*() const { return x; }
bool operator!=(const n_iter y) const { return x != y.x; }
n_iter &operator++() { x++; return *this; }
};
struct sq_iter
{
int x;
int operator*() const { return x*x; }
bool operator!=(const sq_iter y) const { return x != y.x; }
sq_iter &operator++() { x++; return *this; }
};
template <typename T>
struct proxy
{
const range &orig;
T begin() const { return { orig.a }; }
T end() const { return { orig.b }; }
};
proxy<n_iter> numbers() { return {*this}; }
proxy<sq_iter> squares() { return {*this}; }
};
int main()
{
range r{ 1, 5 };
for (auto x : r.numbers())
{ printf("%d\n", x); }
for (auto x : r.squares())
{ printf("%d\n", x); }
return 0;
}
.file "zoom.cpp"
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "%d\n"
.section .text.unlikely,"ax",@progbits
.LCOLDB1:
.section .text.startup,"ax",@progbits
.LHOTB1:
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB22:
.cfi_startproc
pushq %rbx
.cfi_def_cfa_offset 16
.cfi_offset 3, -16
movl $1, %ebx
.L2:
movl %ebx, %esi
xorl %eax, %eax
movl $.LC0, %edi
addl $1, %ebx
call printf
cmpl $5, %ebx
jne .L2
movl $1, %esi
movl $.LC0, %edi
xorl %eax, %eax
call printf
movl $4, %esi
movl $.LC0, %edi
xorl %eax, %eax
call printf
movl $9, %esi
movl $.LC0, %edi
xorl %eax, %eax
call printf
movl $16, %esi
movl $.LC0, %edi
xorl %eax, %eax
call printf
xorl %eax, %eax
popq %rbx
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE22:
.size main, .-main
.section .text.unlikely
.LCOLDE1:
.section .text.startup
.LHOTE1:
.ident "GCC: (exherbo gcc-4.9.2) 4.9.2"
.section .note.GNU-stack,"",@progbits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment