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

C++: How to use set_intersection on two vectors containing user-defined structs?

本文关键字:向量 两个 intersection set 包含 用户 结构 定义 C++      更新时间:2023-10-16

我有两个向量,其中充满了非常简单的结构:

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对象之间的相等。。。

任何帮助都将不胜感激。

首先,当你用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); 
    }
};