I'm trying to get to grip with functors, but it's a long, hard struggle. Can
some C++ guru explain to me why my approach, below, is a pile of poo?
Many thanks,
Angus
// I have some data:
vector<double> somedata = ...;
// References to some of this data are placed in a list...
typedef vector<double>::iterator BinItem;
list<BinItem> bl = ...;
// I want to search this list to find if it contains data of a particular
value, +- some tolerance value:
double const tol = 1.0e-08;
double const desired_value = ...;
find(bl.begin(), bl.end(), CompareWithinTolerance(desired_value, tolerance));
// My question is, is there a better way to define the functor than this?
// Let's ignore the "make it generic" arguments for now. I'm trying to
// understand how these things work.
namespace {
struct CompareWithinTolerance {
CompareWithinTolerance(double const & dv, double t)
: desired_value(dv), tol(t) {}
double desired_value;
double tol;
};
// Can't have operator!= within the class because find() contains:
// InputIterator find (InputIterator first, InputIterator last, const T& value)
// { while (*first != value) ...}
bool operator!=(vector<double>::const_iterator it,
CompareWithinTolerance const & cwt)
{
return (cwt.desired_value - *it) < cwt.tol;
}
} // anon namespace