Re: Must second bind2nd parameter be constant for loop?
Pete Becker wrote:
Rex Kerr wrote:
I'm trying to compare two vectors to ensure that their values are equal
within a tollerance (easy, std::equal with a binary predicate), but my
definition of equal also allows for a certain number of values to lie
outside of the tollerance, so I want something like std::count_if that
takes two ranges and passes them to a binary op.
count_if won't help here, because it doesn't take two ranges.
If you insist on using algorithms from the standard library, I think
you've got a two step process. First, use transform to walk through the
two ranges and write out a sequence giving the result of each comparison
of pairs of values. Then walk through that sequence and count the number
of values that are out of tolerance.
If you want to roll your own algorithm, it's straightforward:
template <class InIt1, class InIt2>
int out_of_tolerance(InIt1 first1, InIt1 last1, InIt2 first2)
{
int count = 0;
while (first1 != last1)
if (compare(*first1++, *first2++))
++count;
return count;
}
Can it not be done in one step using a standard algorithm?
#include <stdio.h>
#include <numeric>
#include <functional>
int compare(int a, int b) { return abs(a - b) >= 2; }
int const a[5] = { 0, 1, 2, 3, 4 };
int const b[5] = { 0, 2, 1, 1, 6 };
int main()
{
int x = out_of_tolerance(a, a + 5, b);
int y = std::inner_product(a, a + 5, b, int(), std::plus<int>(),
compare);
printf("%u\n", x);
printf("%u\n", y);
}
[max@k-pax test]$ bin/test
2
2
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]