Re: How to create custom iterator for use with std::copy?
In article <4456612e$1@mamba.>,
"Siegfried Heintze" <siegfried@heintze.com> wrote:
What is the minimum I must type to create a custom iterator that will allow
me display my iterator on std::cout using std::copy?
Try it.
class MyIter
{
}
int main()
{
copy( MyIter...
OK, apparently we need at least one constructor...
class MyIter
{
public:
MyIter();
};
int main()
{
copy( MyIter(), ...
Well, now we need some way of creating two different objects of the same
type...
class MyIter
{
public:
MyIter();
MyIter( int v );
};
int main()
{
copy( MyIter(), MyIter( 7 ), ostream_iterator<...
OK, what does a MyIter contain? Let's just have it hold ints...
int main()
{
copy( MyIter(), MyIter( 7 ), ostream_iterator<int>( cout ) );
}
Now try to compile it and it will tell you what functions are missing.
It's fun!
Here is one I came up with...
class fibonacci:
public std::iterator< std::forward_iterator_tag, int >
{
int prev_value, value, max;
public:
fibonacci(): prev_value(0), value(0), max(0) { }
explicit fibonacci(int m): prev_value(0), value(1), max(m) { }
const int operator*() const { return value; }
fibonacci& operator++()
{
int tmp = value;
value += prev_value;
prev_value = tmp;
return *this;
}
fibonacci operator++(int)
{
fibonacci tmp(*this);
++(*this);
return tmp;
}
friend bool operator==(const fibonacci& lhs, const fibonacci& rhs)
{
bool result = false;
if ( lhs.value == 0 && rhs.value == 0 )
result = true;
else if ( rhs.value == 0 && !( lhs.value < lhs.max ) )
result = true;
else if ( lhs.value == 0 && !( rhs.value < rhs.max ) )
result = true;
else if ( lhs.prev_value == rhs.prev_value
&& lhs.value == rhs.value && lhs.max == rhs.max )
result = true;
return result;
}
};
bool operator!=(const fibonacci& lhs, const fibonacci& rhs) {
return !(lhs == rhs);
}