Re: Must second bind2nd parameter be constant for loop?
Matthew T. Staebler wrote:
Carlos Moreno wrote:
James Kanze wrote:
Note too that the predicate must be copiable, and the algorithm
can copy it as many times and whenever it wants.
So, you're suggesting that the implementation could be recursive?
I would hate to put words into James's mouth, but I assume that he was
cautioning someone using algorithms such as count_if and equal from
relying on predicates that store values that change as elements of the
range are visited.
In the EqualWithTolerance class defined above,
there is an int nOut_ member whose value should be based upon the
results of previous visits to other elements of the range. However, it
is not guaranteed that the EqualWithTolerance object that visits one
element will be the same as the EqualWithTolerance object that visits
another element, as the implementation of the algorithm has the
flexibility to copy the predicate object as it sees fit. It would be a
perfectly legal implementation of the algorithm to create a unique copy
of the passed predicate object for every element of the range. Using
such an implementation with the EqualWithTolerance class as a predicate
would mean that every element would be visited with an
EqualWithTolerance object whose nOut_ member had a value of 0.
While it is probably unlikely (although still legal) for an
implementation of count_if and equal to copy the predicate object in
such a fashion, it is much more likely for other algorithms such a
find_if to copy the predicate object. If one is in the habit of
ignoring the possibility for unlikely algorithms such as count_if, it
is much easier to forget about the possibility for likely algorithms
such as find_if.
I'm not sure about the likelyhood. Count_if is a perfect
example of an algorithm which can be parallelized on a modern,
One fairly simple solution to this problem is to use a reference for
the mutable values in your predicate object. Changing the nOut_ member
in EqualWithTolerance from an int to an int& and supplying an int& to
the constructor of EqualWithTolerance will resolve the issue.
It still doesn't guarantee order. (And it raises some
interesting questions with regards to thread safety in a
parallel implementation. Given the importance he gave to
performance, I suspect that Stepanov's original intent was to
allow parallel implementations.)
James Kanze (GABI Software) email:email@example.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]