How to create custom iterator for use with std::copy?

  • Thread starter Siegfried Heintze
  • Start date
S

Siegfried Heintze

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?
Thanks,
Siegfried
 
D

Daniel T.

"Siegfried Heintze said:
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);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top