簡體   English   中英

C++ - 查找兩個范圍的交集

[英]C++ - Finding intersection of two ranges

在 C++ 中找到兩個范圍交集的最佳方法是什么? 例如,如果我有一個范圍為 [1...20] 包括在內,另一個范圍為 [13...45] 包括在內,我想得到 [13...20],因為這是它們之間的交集。

我想過在 C++ 中使用本機集合交集函數,但我首先必須將范圍轉換為集合,這對於大值會花費太多計算時間。

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

為了完整起見,我想添加一個“增強答案”。

如果您已經在使用 boost,則無需編寫自己的代碼,但可以僅使用標頭

#include <boost/numeric/interval.hpp>

並使用intersect函數處理類型interval<T>

簡單的答案是找到交集范圍的結束值,然后在這個范圍內迭代。

比如說范圍[l1, r1] , [l2, r2]它們之間的交集可以計算為:

 if ((r1 < l2) ||  (r2 < l1)) then no intersection exits.
 else l = max(l1, l2) and r = min(r1, r2)

只需遍歷范圍[l, r]即可獲得交集值。

在 2018 年,強烈推薦使用std::set_intersectionhttps 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 << ' ';
}

輸出:

5 7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM