Connecting Tech Pros Worldwide Help | Site Map
 
 
LinkBack Thread Tools Search this Thread
  #1  
Old May 1st, 2006, 08:45 PM
Siegfried Heintze
Guest
 
Posts: n/a
Default How to create custom iterator for use with std::copy?

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


  #2  
Old May 1st, 2006, 10:15 PM
Daniel T.
Guest
 
Posts: n/a
Default Re: How to create custom iterator for use with std::copy?

In article <4456612e$1@mamba.>,
"Siegfried Heintze" <siegfried@heintze.com> wrote:
[color=blue]
> 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?[/color]

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);
}
 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 205,338 network members.