Angus Leeming <[EMAIL PROTECTED]> writes:
| 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?
Pile of poo.
struct IsWithinTolerance {
IsWithinTolerance(double dv, double t)
: value(dv), tol(t) {}
bool operator()(double db) const {
// fix this one yourself
return (abs(value - db) < tol;
}
private:
double value;
double tol;
};
vector<bouble> vb;
vector<double>::const_iterator cit =
find_if(vb.begin(), vb.end(), IsWithinTolerance(desired_value, tol));
std::find does not take an functor... std::find_if does.
|
| 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
|
--
Lgb