What is the best way to find the intersection of two ranges in C++? For example, if I have one range as [1...20] inclusive, and another as [13...45] inclusive, I want to get [13...20], as that is the intersection between them.
I thought about using the native set intersection function in C++, but I would first have to convert the range into a set, which would take too much computation time for large values.
I thought about using the native set intersection function in C++, but I would first have to convert the range into a set, which would take too much computation time for large values. Just write a bunch of if s. set_intersection takes input and output iterators, so you don't have to convert the range into set but...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With