C++;-求两个范围的交集 在C++中找到两个范围的交集的最佳方法是什么?例如,如果一个范围包含[1…20],另一个范围包含[13…45],我希望得到[13…20],因为这是它们之间的交点 我考虑在C++中使用本机集合交集函数,但我首先必须将范围转换成一个集合,这将占用太多的计算时间。大值< < /P> 交集={STD:::max(ARG1.min,ARG2.min),STD::MIN(ARG1.MAX,ARG2.max)}; intersection = { std::max(arg1.min, arg2.min), std::min(arg1.max, arg2.max) }; if (intersection.max < intersection.min) { intersection.markAsEmpty(); } if(交叉点最大值
为了完整起见,我想添加一个“增强答案” 如果您已经在使用boost,则不需要编写自己的代码,只需获取标题即可C++;-求两个范围的交集 在C++中找到两个范围的交集的最佳方法是什么?例如,如果一个范围包含[1…20],另一个范围包含[13…45],我希望得到[13…20],因为这是它们之间的交点 我考虑在C++中使用本机集合交集函数,但我首先必须将范围转换成一个集合,这将占用太多的计算时间。大值< < /P> 交集={STD:::max(ARG1.min,ARG2.min),STD::MIN(ARG1.MAX,ARG2.max)}; intersection = { std::max(arg1.min, arg2.min), std::min(arg1.max, arg2.max) }; if (intersection.max < intersection.min) { intersection.markAsEmpty(); } if(交叉点最大值,c++,range,intersection,set-intersection,C++,Range,Intersection,Set Intersection,为了完整起见,我想添加一个“增强答案” 如果您已经在使用boost,则不需要编写自己的代码,只需获取标题即可 #include <boost/numeric/interval.hpp> #包括 并使用intersect函数处理类型interval在2018年,强烈建议使用std::set_intersection:。它不必来自std::set,但必须对范围进行排序 例如: #include <iostream> #include <vector> #inc
#include <boost/numeric/interval.hpp>
#包括
并使用
intersect
函数处理类型interval
在2018年,强烈建议使用std::set_intersection
:。它不必来自std::set
,但必须对范围进行排序
例如:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v1{1,2,3,4,5,6,7,8};
std::vector<int> v2{ 5, 7, 9,10};
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<int> v_intersection;
std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(v_intersection));
for(int n : v_intersection)
std::cout << n << ' ';
}
简单的答案是找到相交范围的端点值,然后在这个范围内迭代 比如说,对于范围
[l1,r1]
,[l2,r2]
它们之间的交点可以计算为:
if ((r1 < l2) || (r2 < l1)) then no intersection exits.
else l = max(l1, l2) and r = min(r1, r2)
如果((r1
只需迭代范围
[l,r]
即可获得交集值。如果s.set\u交集使用输入和输出迭代器,则只需编写一组,因此不必将范围转换为集合,而是。。。范围到底是什么?你有没有看过这个:这不完全一样,需要更多的内存。运算需要的是区间的交集,正如它们的上下限所规定的那样,而不是对象集的交集。
if ((r1 < l2) || (r2 < l1)) then no intersection exits.
else l = max(l1, l2) and r = min(r1, r2)