Re: Traversing multiple vectors "in parallel"
Raphael Simon wrote:
Would you mind elaborating on how one would go writing an
iterator that would say add the 4 integers that are in each index of 4
integer vectors?
The important thing about an iterator is mainly that it provides operator++,
operator!= (and maybe operator==) and unary operator*, some algorithms
might need a nested value_type typedef and maybe some further code to make
iterator_traits work. Haven't played with the latter though, so I can't
tell you more.
Now:
struct my_iterator
{
typedef std::vector<unsigned>::iterator iterator_base;
my_iterator( iterator_base i1, iterator_base i2):
m_i1(i1), m_i2(i2)
{}
unsigned operator*() const
{ return *m_i1+*m_i2; }
void operator++() //TODO: correct returntype
{
++m_i1;
++m_i2;
}
friend bool operator==(my_iterator const& i1, my_iterator const& i2)
{
bool b1 = i1.m_i1==i2.m_i1;
bool b2 = i1.m_i2==i2.m_i2;
// if this fires, iterators are shifted, i.e. the sequences
// have different sizes.
assert(b1==b2);
return b1;
}
friend bool operator!=(my_iterator const& i1, my_iterator const& i2)
{ return !(i1==i2); }
private:
iterator_base m_i1;
iterator_base m_i2;
};
vector<unsigned> v1, v2;
....
for( my_iterator it(v2.begin(), v2.begin()), end(v1.end(), v2.end());
it!=end;
++it)
{
std::cout << "sum = " << *it << std::endl;
}
Now, Boost's zip_iterator rules. This here is basically the same, but much,
much more premitive.
Uli