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.
In 2018, the use of
std::set_intersection
is highly recommended: https://en.cppreference.com/w/cpp/algorithm/set_intersection. It doesn't have to be from astd::set
but the ranges do have to be sorted.Example:
Output:
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
and use the
intersect
function dealing with the typeinterval<T>
.