By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,111 Members | 1,675 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,111 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
May 1 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
In article <4456612e$1@mamba.>,
"Siegfried Heintze" <si*******@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);
}
May 1 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.