【问题标题】:std::set_intersection, Intersection list with offsetstd::set_intersection,带偏移量的交集列表
【发布时间】:2015-12-28 20:22:08
【问题描述】:

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

我还希望能够获得带有偏移量的交集。例如给定两个向量 {1,2,3,4,6,8} 和 {5, 7, 9,10} 。与偏移量 2 的交点是 { 3,8 },因为 3 + 2 = 5 和 8 + 2 = 10。

我想下面的代码应该可以工作,但是 {3,8} 我得到了 {3,6,8} 。我不知道如何使用 std::set_intersection 的比较器功能。我错过了什么?

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

【问题讨论】:

  • this,因为equiv(a, b) == !comp(a, b) &amp;&amp; !comp(b, a)所以6 == 7因为!((6+2) &lt; 7) &amp;&amp; !((7+2) &lt; 6)

标签: c++ c++11 vector


【解决方案1】:

this,因为

类型T满足Compare if

  • T 类型满足BinaryPredicate,并且

给定

  • compCompare 类型的对象

  • equiv(a, b),等价于!comp(a, b) &amp;&amp; !comp(b, a)的表达式

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

  • 对于所有acomp(a,a)==false

  • 如果comp(a,b)==true那么comp(b,a)==false

  • 如果comp(a,b)==truecomp(b,c)==true 然后comp(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) &lt; 7) &amp;&amp; !((7+2) &lt; 6)

实际上,您的lessThanWithOffset 不符合标准,因为 equiv(A(6), A(8)) == trueequiv(A(8), A(10)) == true,但 equiv(A(6), A(10)) == false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多