1

I am confused on comparing iterators in C++. With the following code:

std::iterator< std::forward_iterator_tag, CP_FileSystemSpec> Iter1;
std::iterator< std::forward_iterator_tag, CP_FileSystemSpec> Iter2;

while( ++Iter1 != Iter2 )
{

}

The error is:

error: no match for 'operator++' in '++Iter1'

I seem to recall that you could not do what the code above is doing. But I dont quite know how to do the comparison.

4 Answers 4

6

std::iterator is not an iterator in itself, but a base class other iterators could inherit from to get a few standard typedefs.

template<class Category, class T, class Distance = ptrdiff_t, class Pointer = T*, class Reference = T&> 
struct iterator 
{ 
    typedef T value_type; 
    typedef Distance difference_type; 
    typedef Pointer pointer; 
    typedef Reference reference; 
    typedef Category iterator_category; 
};
Sign up to request clarification or add additional context in comments.

Comments

2

This error has nothing to do with the comparison- it's telling you that that specific iterator does not support incrementing.

1 Comment

so how does one overcome something like this. I assume that I could add incrementing for this iterator in a header for where this is defined?
2

You're supposed to derive from std::iterator -- instantiating it directly makes no sense.

Comments

0

To make that sample work, use an iterator that is backed by an sequence, for instance a vector:

std::vector<int> foo(10); // 10 times 0

std::vector<int>::iterator it1 = foo.begin();
std::vector<int>::iterator it2 = foo.end();

while(++it1 != it2) {
    // do stuff
}

Note that this is not the canonical way to iterate over a collection. It is also tricky, because it skips the first element of the sequence. Use this:

for(std::vector<int>::iterator it = foo.begin(); it != foo.end(); it++) {
    // do stuff
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.