std :: set_intersection,带偏移的交点列表

时间:2015-12-28 06:31:21

标签: c++ c++11 vector

我需要获取两个向量之间的交集列表。在我的情况下,向量是用户类型的向量。因此,为了获得封装的数字,我必须使用比较器函数。

此外,我希望能够获得与offSet的交集。例如,给出两个向量{1,2,3,4,6,8}和{5,7,9,10}。与offSet 2的交点为{3,8},因为3 + 2 = 5且8 + 2 = 10。

我认为下面的代码应该可行但是{3,8}我得到{3,6,8}。我无法弄清楚如何使用std :: set_intersection的comparer函数。我错过了什么?

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>


struct A 
{
    A ( int in ) { a = in; }
    int getNumber() { return a; }

    bool operator< ( A rhs )
    {
        return this->a < rhs.a;
    }
    int a; 
};

int main()
{
    std::vector<A> v1{1,2,3,4,6,8};
    std::vector<A> v2{5,  7,  9,10};
    int offSet = 2;
    auto lessThanWithOffset = [offSet]( A lhs,  A rhs)
    {
        return lhs.getNumber() + offSet < rhs.getNumber();
    };

    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());

    std::vector<A> v_intersection;
    std::set_intersection(v1.begin(), v1.end(),
                          v2.begin(), v2.end(),
                          std::back_inserter(v_intersection), lessThanWithOffset);

    for(auto n : v_intersection)
        std::cout << n.getNumber() << ' ';
}

1 个答案:

答案 0 :(得分:1)

请参阅this,因为

  

如果

T类型满足Compare      
      
  • T类型符合BinaryPredicate
  •   
     

鉴于

     
      
  • compCompare

  • 类型的对象   
  • equiv(a, b),一个等同于!comp(a, b) && !comp(b, a)

  • 的表达式   
     

以下表达式必须有效并具有指定的效果

     
      
  • 适用于所有acomp(a,a)==false

  •   
  • 如果comp(a,b)==truecomp(b,a)==false

  •   
  • 如果comp(a,b)==truecomp(b,c)==truecomp(a,c)==true

  •   
  • 适用于所有aequiv(a,a)==true

  •   
  • 如果equiv(a,b)==true,则equiv(b,a)==true

  •   
  • 如果equiv(a,b)==trueequiv(b,c)==true,则equiv(a,c)==true

  •   

所以equiv(A(6), A(7)) == true因为!((6+2) < 7) && !((7+2) < 6)

实际上,您的lessThanWithOffset未遵守标准,因为 equiv(A(6), A(8)) == trueequiv(A(8), A(10)) == true,但equiv(A(6), A(10)) == false

相关问题