Re: std::max_element iterators
Am 19.10.2010 10:53, schrieb tf:
Why does std::max_element need a ForwardIterator? Couldn't it get by
with just an InputIterator?
... okay nevermind, google answered that, but leaves another
question open. The above seems like a silly requirement to impose on
the caller. Why not just define it to return *iter instead of iter?
This would not help either. Once you have applied any increment
operation on an object that corresponds to an input iterator, you
cannot dereference any copies of it. The only thing that you could
reasonably do with input-iterator-only types is to copy *every*
element of the iterated range into a local variable and to ensure that
your current max value is also a local variable (you can rid of one
of these locals, but not of both) and you need to copy the result as
well.
Then there would be no need to save the iterator. I can't recall
ever using std::???_element without immediately dereferencing it w/in
the RHS anyway. What use is it to know the index?
Often it is sufficient to know the position of the maximum. This allows
to transport this as a usually much cheaper information than the actual
value.
I needed the minimum *and* maximum, so I had to define my own
function anyway. This would've been nice for testing, though.
In C++0x you will have minmax_element, but it also returns a pair of
(forward) iterators, so it does not help you when you are
asking for being able to evaluate a pure input iterator.
It seems to me that what you better should use is the algorithm
std::for_each combined with a corresponding accumulating
function object (Or use the boost Accumulators library that
could be used in a similar manner).
Another way of looking at your problem is to recognize that you
could take advantage of reduction algorithm (not part of [algorithm])
that corresponds to the reduction operator of the programming language
APL. It is very similar to for_each, but it does not return the
function object, it only returns the result type ("domain") of such a
function object - "Elements of Programming" discusses this algorithm.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]