Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrap std::iterator in C++

Tags:

c++

iterator

I have a need to wrap a vector iterator, but don't like the idea to rewrite it from scratch. And I can't subclass it as far as vector iterator doesn't seem to be cross-platform. At least gnu and ibm ones look different.

What I want to do is the following:

class MyContainer {
    vector<double> data;
    vector<int> indices;

    iterator
    begin()
    { return my_iterator(data, indices.begin()); }

    iterator
    end()
    { return my_iterator(data, indices.end()); }
}

MyContainer  cont;

Where indices vector contains integer positions within the data vector. Data is supposed to be much much bigger than the indices.

So I need an iterator that can go through the indices in any direction like a normal vector iterator does with the only exception: it must return a value of data vector when the value is going to be accessed. e.g.:

for(MyContainer::iterator it = cont.begin(); it != cont.end(); it++) {
    cout << *it << endl; // values of data should appear here
}

Basically it should look like a normal collection for the std world. You can iterate it in whatever direction you want, you can sort it, run unique, find_if, etc...

any simple solution?

like image 793
novak Li Avatar asked Dec 17 '22 19:12

novak Li


2 Answers

There's a great Boost library for defining custom iterators. You need to provide a class with a few methods:

i.dereference()  Access the value referred to
i.equal(j)       Compare for equality with j
i.increment()    Advance by one position
i.decrement()    Retreat by one position
i.advance(n)     Advance by n positions
i.distance_to(j) Measure the distance to j

Then you get the rest from the iterator_facade.

Good luck!

like image 97
Daniel Lidström Avatar answered Dec 29 '22 08:12

Daniel Lidström


This looks a lot like a permutation_iterator, one of the "built in" adapters from the Boost.Iterator Library

See this example (modified from the Boost docs) on codepad.

like image 39
Éric Malenfant Avatar answered Dec 29 '22 10:12

Éric Malenfant