Wrap std :: iterator in C ++

I need to wrap a vector iterator, but I don't like the idea of ​​rewriting it from scratch. And I cannot subclass it, since the vector iterator does not seem cross-platform. At least gnu and ibm look different.

I want to do 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; 

If the index vector contains integer positions in the data vector. It is assumed that the data will be much larger than the indexes.

So, I need an iterator that can go through indices in any direction, such as a normal vector iterator, with one exception: it must return the value of the data vector when the value is accessed. eg:.

 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 regular collection for the std world. You can repeat it in any direction you want, you can sort it, run unique, find_if, etc.

any simple solution?

+4
source share
3 answers

This is very similar to permutation_iterator , one of the built-in adapters of the Boost.Iterator library

See this example (modified from Boost docs) in the code.

+4
source

There's a great Boost library for defining custom iterators. You need to provide a class in several ways:

 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 iterator_facade .

Good luck

+6
source

There is nothing in the C ++ standard library, but you can probably get boost::iterator_adapter to do what you want. A preliminary inspection suggests that you need to override iterator_adapter::dereference and iterator_adapter::equal .

 template <typename _Scalar=double, typename _Idx=int, typename _Seq=std::vector<_Scalar>, typename _IdxVector=std::vector<_Idx> > class SelIter : public boost::iterator_adaptor< SelIter<_Scalar, _Idx>, typename _IdxVector::iterator, _Scalar > { public: typedef boost::iterator_adaptor< SelIter, typename _IdxVector::iterator, _Scalar > Base; SelIter(_Seq& scalars, _IdxVector& idxs); SelIter(_Seq& scalars, typename _IdxVector::iterator pi); typename Base::reference dereference() const; bool equal(const SelIter& x) const; private: // ... } 
+2
source

All Articles