Boost logo

Ublas :

From: Russ (c.r.coggrave_at_[hidden])
Date: 2006-04-18 20:17:31


I see that the following iterator classes support binary subtraction:

triangular_matrix::iterator1
triangular_matrix::const_iterator1
triangular_matrix::iterator2
triangular_matrix::const_iterator1

e.g. Extract from triangular.hpp, triangular_matrix::const_iterator1::operator-

BOOST_UBLAS_INLINE
difference_type operator - (const const_iterator1 &it) const {
  BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());
  BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());
  return it1_ - it.it1_;
}

However, binary subtraction is not possible on sparse matrix iterators (I
haven't checked dense matrix iterators). It would be nice if support for
iterators was consistent...it would seem that a small addition to the iterator
classes in iterator.hpp would fix this. Unfortunately, I am still fairly new to
uBlas and don't want to introduce any mistakes at this level...does anyone else
fancy having a go at this?

Why is this operator useful?

// Initialise it1 iterator
typename M::const_iterator1 it1 (Matrix.begin1());
// Compute number of elements in this sequence
difference_type size1(Matrix.end1() - it1); // Use binary subtraction op
while (--size1 >= 0) {
#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION
  // Initialise it2 iterator
  typename M::const_iterator2 it2 (it1.begin ());
  // Compute number of elements in this sequence
  difference_type size2 (it1.end () - it2);
#else
  // Initialise it2 iterator
  typename M::const_iterator2 it2 (begin (it1, ublas::iterator1_tag ()));
  // Compute number of elements in this sequence
  difference_type size2 (end (it1, ublas::iterator1_tag ()) - it2);
  #endif
  // Inner loop
  while (--size2 >= 0) {
    // Do something with *it2 here
    // Advance inner iterator
    ++it2;
  }
  ++ it1; // Advance outer iterator
}

The important point being that we don't need to call end() methods on every loop
iteration to check for end condition, hopefully providing a small improvement in
performance.

Russ