C++ - Finding intersection of two ranges
simple answer is to just find end values of intersection range and then iterate over this range.
say for the range [l1, r1]
, [l2, r2]
intersection between them can be calculated as:
if ((r1 < l2) || (r2 < l1)) then no intersection exits.
else l = max(l1, l2) and r = min(r1, r2)
just iterate over the range [l, r]
to get the intersection values.
For the sake of completeness I would like to add a 'boost answer'.
If you're already using boost, you don't need to write your own code but can take the header-only
#include <boost/numeric/interval.hpp>
and use the intersect
function dealing with the type interval<T>
.
intersection = { std::max(arg1.min, arg2.min), std::min(arg1.max, arg2.max) };
if (intersection.max < intersection.min) {
intersection.markAsEmpty();
}