Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Finding intersection of two ranges

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.

like image 979
1110101001 Avatar asked Nov 16 '13 20:11

1110101001


People also ask

How do you find the intersection of two ranges in C++?

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...


1 Answers

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.

like image 145
y_159 Avatar answered Oct 29 '22 09:10

y_159