C++ - Finding intersection of two ranges

拈花ヽ惹草 提交于 2019-12-04 01:40:05
intersection = { std::max(arg1.min, arg2.min), std::min(arg1.max, arg2.max) };
if (intersection.max < intersection.min) {
  intersection.markAsEmpty();
}
yau

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

#include <boost/numeric/interval.hpp>

and use the intersect function dealing with the type interval<T>.

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 a std::set but the ranges do have to be sorted.

Example:

#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 << ' ';
}

Output:

5 7
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!