Alon Shmiel
Alon Shmiel

Reputation: 7121

Create a class iterator

I want to create a class iterator that can pass over kinds of A (I mean: linked list and an array [INDEXES]).

how can I do it please?

what should I define in the classes of A, B and C?

class Iterator {
    A* a;
  public:
    A* getnext() {}
    A* getcontant() {}
};

class A {
   public:
     iterator* iterator() {}
};

class B : public A {
    linkedlist* head; // a linked list of nodes
};

class C : public A {
    INDEXES* vec; // vec is an array of objects of INDEXES
};

any help appreciated!

Upvotes: 0

Views: 284

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490098

You probably can't. An iterator (or at least most iterators) are specific to a particular collection.

For example, operator++ for a linked-list iterator will probably do something like location = location -> next; while operator++ for something array-like might do something like ++location; instead.

In theory, you could create a meta-iterator (so to speak) that would work with any iterator that provided a specific interface (e.g., at least ++, * and !=). This is roughly congruent to (a small) part of what concepts were supposed to do. There's still discussion of a "concepts lite" that may provide something similar in the future (at least provide the ability to define such an interface, so you'd be able to directly specify what operations were needed by a particular algorithm).

Such a meta-iterator only really gains much if you do something more than that though, such as providing a number of implementations that allow you to adapt algorithms that use one interface to containers that provide various different interfaces (e.g., could allow applying STL algorithms directly to wxWidgets or Qt collections). The latter a fairly uncommon (at least in C++) simply because it's generally easier to just provide decent iterators in the first place.

Upvotes: 1

Related Questions