TeachMeMaster
TeachMeMaster

Reputation: 51

comparing iterators in C++

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.

Upvotes: 1

Views: 1645

Answers (4)

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76788

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
}

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92261

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

Upvotes: 6

Ben Voigt
Ben Voigt

Reputation: 283634

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

Upvotes: 2

Puppy
Puppy

Reputation: 146930

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

Upvotes: 2

Related Questions