C ++:如何在包含用户定义结构的两个向量上使用set_intersection?

时间:2015-02-25 06:00:03

标签: c++ vector set-intersection

我有两个非常简单的结构:

typedef struct{
    //three vertex ids
    uint a,b,c;

} Face;

我正在尝试像这样运行set_intersection:

set_intersection(listOfFaces1.begin(),listOfFaces1.end(),listOfFaces2.begin(),listOfFaces2.end(), back_inserter(facesToDelete));

我猜我需要以某种方式覆盖某个比较器?但我不确定如何定义两个Face对象之间的相等...

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

首先,当您使用C ++编程时,您可以使用:

struct Face {
    uint a,b,c;
};

这是一个实现operator<的简单策略,适用于标准库中的算法和容器。

struct Face {
    uint a,b,c;

    bool operator<(Face const& rhs) const
    {
       if ( a != rhs.a )
       {
          return ( a < rhs.a);
       }
       if ( b != rhs.b )
       {
          return ( b < rhs.b);
       }
       return ( c < rhs.c);
    }
};

或者,正如@Praetorian所建议的那样,

struct Face {
    uint a,b,c;

    bool operator<(Face const& rhs) const
    {
       return std::tie(a, b, c) < std::tie(rhs.a, rhs.b, rhs.c); 
    }
};