c++ - Is there an STL algorithm to find if an element is present in a container based on some tolerance? -
the problem trying solve following: have container of floating points (vector of double vectors):
std::vector<std::vector<double>> dv { {0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {1.0, 1.0} };
then, assume have new point (double vector):
std::vector<double> v1 {0.0001, 1.0};
i want check if point v1 present in dv container based on tollerance. distance between 2 vectors calculated euclidean distance.
i have looked relevant questions , answers:
and trying use std::find_if()
without success, accepts unary predicate.
at moment came temporary solution. first, created generic function find euclidean distance between 2 vectors:
template <typename inputit1, typename inputit2> double euclideandistance(inputit1 beg1, inputit1 end1, inputit2 beg2) { double val = 0.0; while (beg1 != end1) { double dist = (*beg1++) - (*beg2++); val += dist*dist; } return val > 0.0? sqrt(val) : 0.0; }
second, created check_if
function check if element presented in container based on tolerance (epsilon):
template <typename container, typename element> bool check_if(const container& c, const element& el, const double epsilon = 0.001) { auto pos = c.begin(); (; pos != c.end(); ++pos) { if (euclideandistance(pos->begin(), pos->end(), el.begin()) < epsilon) { return true; } } return false; }
and can use code in context this:
// check if container contains v1 using check_if() if (check_if(dv, v1)) { std::cout << "using check_if() - container contains v1\n"; }
so questions following:
- is there in-house stl algorithm achieve same goal? if no, how improve code? example, i'm not sure how use distance function in
check_in()
instead ofeuclideandistance()
? - i wonder if ashleysbrain suggestion (https://stackoverflow.com/a/3451045/3737891) use
std::set
instead ofstd::vector
make difference having container of floating points?
and trying use std::find_if() without success, accepts unary predicate.
that's want anyway. single argument going elements of vector you're looking in.
std::vector<std::vector<double>> dv{ {0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {1.0, 1.0}}; std::vector<double> v1 {0.0001, 1.0}; auto find_result = std::find_if(begin(dv), end(dv), [&v1](std::vector<double> const &dve) { assert(dve.size() == v1.size()); return euclideandistance(begin(dve), end(dve), begin(v1)) < 0.001; });
on note, if points fixed dimension using vector<double>
not right representation. tuple<double,double>
, or array<double 2>
, or custom class has overloaded operators appropriate replacements.
Comments
Post a Comment