Talk:Generator/Exponential: Difference between revisions
Content added Content deleted
(→C++ code: new section) |
(→C++ code: like this code?) |
||
Line 43: | Line 43: | ||
The C++ code should probably be an implementation of forward_iterator. I'd do it myself, but I don't know how (working on that is what led me back to this page) --[[User:Short Circuit|Michael Mol]] 14:08, 1 July 2011 (UTC) |
The C++ code should probably be an implementation of forward_iterator. I'd do it myself, but I don't know how (working on that is what led me back to this page) --[[User:Short Circuit|Michael Mol]] 14:08, 1 July 2011 (UTC) |
||
:What, like this? <lang Cpp>#include <iostream> |
|||
#include <iterator> |
|||
template<int p> |
|||
class PowerSeq : public std::iterator<std::forward_iterator_tag, int> { |
|||
public: |
|||
PowerSeq(int first = 0 ) { pos = first; } |
|||
int operator *() { return calc(); } |
|||
PowerSeq<p>& operator ++() { |
|||
pos ++; |
|||
return *this; |
|||
} |
|||
PowerSeq<p> operator ++(int) { |
|||
PowerSeq<p> tmp(pos); |
|||
pos ++; |
|||
return tmp; |
|||
} |
|||
protected: |
|||
int pos; |
|||
int calc() { |
|||
int out = pos; |
|||
for (int i = 1; i < p; i++) out *= pos; |
|||
return out; |
|||
} |
|||
}; |
|||
template<int in, int without> |
|||
class PowerSeqFilter : public std::iterator<std::forward_iterator_tag, int> { |
|||
public: |
|||
PowerSeqFilter(int p1 = 0, int p2 = 0) { // NB. should check in != without |
|||
s1 = PowerSeq<in>(p1); |
|||
s2 = PowerSeq<without>(p2); |
|||
if (*s1 == *s2) ++*this; |
|||
}; |
|||
int operator *() { if (*s1 == *s2) ++*this; return *s1; } |
|||
PowerSeqFilter<in, without>& operator ++() { |
|||
do { |
|||
++s1; |
|||
while (*s1 > *s2) ++s2; |
|||
} while (*s1 == *s2); |
|||
return *this; |
|||
} |
|||
PowerSeqFilter<in, without> operator ++(int) { |
|||
PowerSeqFilter<in, without> tmp(*s1, *s2); |
|||
++*this; |
|||
return tmp; |
|||
} |
|||
protected: |
|||
PowerSeq<in> s1; |
|||
PowerSeq<without> s2; |
|||
}; |
|||
int main() |
|||
{ |
|||
PowerSeqFilter<2, 3> f; |
|||
for (int i = 0; i < 30; ++i, f++) { |
|||
if (i >= 20) |
|||
std::cout << i << " " << *f << std::endl; |
|||
} |
|||
}</lang> |
|||
:Personally I find this unnecessarily complicated for the task. --[[User:Ledrug|Ledrug]] 01:58, 2 July 2011 (UTC) |