0

I am writing a Set class in order to get a handle on how they really work, as well as to try to write my own Iterator. As far as I understand an Iterator is just a high level pointer that abstracts, well, iteration through a structure.

That being said I am aware that the important parts of an iterator are the ++ -- and * operations. I have successfully created and tested by in/decrement operators, but I am having a hell of a time conceptualizing what I need to return when I deference the Iterator.

Do I return the object it's pointing to?

Here is the relevant code in my set.h file:

class Set{
private:
    struct Elem {
        ELEMENT_TYPE info;
        Elem *prev, *next;
    };
    Elem *_head, *_tail;
    int _size;

public:
    //...

    class Iterator{
        private:
            Elem * _cur;

    public:
        Iterator(){}
        Iterator( Elem* );

        Iterator operator++( int );
        Iterator operator++();
        Iterator operator--( int);
        Iterator operator--();

        bool operator==( const Iterator& rhs );
        bool operator!=( const Iterator& rhs );

        Elem operator*();

    };

     //...
};

Like I said, I am returning the "Elem" that the Iterator is pointing to, is that correct?

Set::Elem* Set::Iterator::operator*(){

return _cur;
}
Joshua
  • 4,270
  • 10
  • 42
  • 62

3 Answers3

3

Usually you'd return the element pointed to, by reference.

Elem&       operator*()       { return *_cur; }

It does depend a bit on the iterator type, though. Certain iterators (input iterators, e.g.) wouldn't necessarily return references.

sehe
  • 374,641
  • 47
  • 450
  • 633
  • @Joshua: Since `elem` is an internal node type, more like the iterator should return a reference to a `ELEMENT_TYPE` – Mooing Duck Mar 19 '13 at 00:59
1

You'd normally return a reference, something like:

ELEMENT_TYPE & operator*() { return _cur->info;}
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
user1998586
  • 762
  • 7
  • 13
0

The * operator should return either the value or a reference

Set::Elem &Set::Iterator::operator*() {
    return *_cur;
}

const Set::Elem &Set::Iterator::operator*() const {
    return *_cur;
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • Usually, a `const` iterator returns a reference to mutable data, and a `const_iterator` returns a reference to immutable data. Iterators (including pointers) are weird like that. `const char*` vs `char*const`. – Mooing Duck Mar 19 '13 at 01:00