C++ - Finding intersection of two ranges

淺唱寂寞╮ 提交于 2019-12-04 18:00:13

问题


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.


回答1:


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



回答2:


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>.




回答3:


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


来源:https://stackoverflow.com/questions/20023482/c-finding-intersection-of-two-ranges

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