C ++ - 查找两个范围的交集 [英] C++ - Finding intersection of two ranges

查看:32
本文介绍了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();
}

这篇关于C ++ - 查找两个范围的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆