Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic/polymorphic iterators

What is the best way to implement getIterator? Depending on a condition, I want to return the corresponding iterator.

// global variables
vector<int> myVector;
set<int> mySet;

vector<int>/set<int>::iterator getIterator(bool someCondition) {
    if (someCondition) return mySet.begin();
    else return myVector.begin();
}

Please resist 'wise' responses like "don't use global variables" etc. I just want to know if there is a way to "generalize" both set and vector iterators, this example is just crafted to keep things simple.

Cheers

like image 808
turing_machine Avatar asked Dec 06 '25 09:12

turing_machine


1 Answers

Yes, iterators can be generalized, but you will probably need to write a wrapper class. There are several options for implementing it. Obviously, you will need to store an actual iterator inside the class and have a way to determine, which iterator it is. For example:

class MyIter {
...
private:
    union {
        std::vector<int>::iterator vec_iter;
        std::set<int>::iterator set_iter;
    }
    bool is_vec_iter; /* or like in an example above, enum { vector, set} type_t; */
};

It should be pretty obvious, how to construct an object of such class. The interesting part is implementing the interface, i.e. dereferencing, incrementing, comparing iterators.

Probably a good thing to take a look at is boost::iterator_facade: http://www.boost.org/doc/libs/1_53_0/libs/iterator/doc/iterator_facade.html. It's a helper template, which implements most of iterator's operations using only few methods for dereferencing and traversal which you must provide. Even if you decide to implement everything from scratch, iterator_facade is a good example to start with.

like image 154
Mikhail Maltsev Avatar answered Dec 07 '25 22:12

Mikhail Maltsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!