Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic iterator

I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list.

The custom list defines an iterator;

class Iterator: public std::iterator<std::forward_iterator_tag, T> {     // ... }  Iterator begin() {     return (Iterator(root)); }  Iterator end() {     return (Iterator(NULL)); } 

with the appropriate operators overloaded.

Ideally, I would like to do this;

class Foo { public:     Foo() {         std::list<int> x;         std::vector<int> y;         custom_list<int> z;          iter = x.begin(); // OR         iter = y.begin(); // OR         iter = z.begin();          // ...     }; private:     std::iterator<int> iter; }; 

But obviously these are all iterators of different types. I can assume all the containers are of the same type however.

Is there an elegant way to solve this problem?

like image 712
Mark Avatar asked Aug 13 '08 15:08

Mark


People also ask

What is iterator with example?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java.util package.

What is generic data type?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

Why do you need iterators in generic collections?

Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque, and all implemented classes of Map interface.


2 Answers

Here are some articles you might find of interest

Giving STL Iterators a Base Class

Type Erasure for C++ Iterators

any_iterator Class Reference

like image 185
David Sykes Avatar answered Oct 14 '22 15:10

David Sykes


Better late than never...

The latest issue of C-Vu turned up and guess what was in it: That's right, iterators that do exactly what you wanted.

Unfortunately you need to become a member of the ACCU to view the magazine (the article references the Overload article from 2000 that David links to). But for a measly price a year you get a nice magazine to read, conferences and user groups. When you become a member you can view PDF's of the back issues so what are you waiting for?

like image 37
graham.reeds Avatar answered Oct 14 '22 14:10

graham.reeds