Boost logo

Boost :

From: Daniel Frey (daniel.frey_at_[hidden])
Date: 2002-05-17 09:19:47


Damien Fisher wrote:
>
> > template< class Iterator >
> > bool is_single_element( Iterator first, const Iterator& last )
> > {
> > return first != last && ++first == last;
> > }
> >
> > template< class Container >
> > bool is_single_element( const Container& container )
> > {
> > return !container.empty() &&
> > ++Container::const_iterator( container.begin() ) ==
> > container.end();
> > }
>
> I know was the one who wrote it, but I personally don't like the one
> taking a container :).

And the version taking iterators could be renamed to 'is_distance_1' or
something similar, at least it looks strange to me to call a function
'is_single_element' with two iterators.

> Aren't iterators generally supposed to be "cheap" to copy? Anyway, even
> if they aren't, one could use boost::call_traits for the 2nd parameter.

Well, cheap is relative. These helpers will be used inside algorithms
where every single temporary is IMHO important. It's good to have a
compiler that can optimize temporaries away, but it's better not to have
them in the code itself.

> When I get some time (hopefully this weekend) I'll write up distance_n
> (which I personally find more appealing than is_single_element as it is
> more STL-ish in its naming).

How about:

template< typename Iterator >
bool is_distance( Iterator first,
                  call_traits< Iterator >::param_type last, // Add
const?
                  int distance ) // Should have a default?
{
   while( distance >= 0 && first != last ) {
      ++first;
      --distance;
   }

   return distance == 0;
}

Regards, Daniel

--
Daniel Frey
aixigo AG - financial training, research and technology
Schloß-Rahe-Straße 15, 52072 Aachen, Germany
fon: +49 (0)241 936737-42, fax: +49 (0)241 936737-99
eMail: daniel.frey_at_[hidden], web: http://www.aixigo.de

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk