C ++ - 查找两个范围的交集

2022-01-24 00:00:00 intersection range set-intersection c++

在 C++ 中找到两个范围交集的最佳方法是什么?例如,如果我有一个包含 [1...20] 的范围,另一个包含 [13...45] 的范围,我想获得 [13...20],因为这是它们之间的交集.

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.

我曾想过在 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.

推荐答案

intersection = { std::max(arg1.min, arg2.min), std::min(arg1.max, arg2.max) };
if (intersection.max < intersection.min) {
  intersection.markAsEmpty();
}

相关文章