c ++中一对对象的映射比较器

map comparator for pair of objects in c++

我想使用地图根据成员输入向量计算对象对。如果为此目的有更好的数据结构,请告诉我。 我的程序 returns 一个 int 向量列表。每个 int 向量是两个 int 向量(一对 int 向量)之间比较的输出。然而,比较的输出可能不同,尽管两个 int 向量相同(可能顺序不同)。我想存储每对 int 向量产生了多少个不同的输出(int 向量)。

假设我可以使用 .inp()

访问对象的 int 向量

(a1.inp() == a2.inp() && b2.inp() == b1.inp())(a1.inp() == b2.inp() and b1.inp() == a2.inp()).

时,两对 (a1,b1)(a2,b2) 应视为相等

This answer 说:

The keys in a map a and b are equivalent by definition when neither a < b nor b < a is true.

class SomeClass
{
    vector <int> m_inputs;
public:
    //constructor, setter...
    vector<int> inp() {return m_inputs};
}

typedef pair < SomeClass, SomeClass > InputsPair;
typedef map < InputsPair, size_t, MyPairComparator > InputsPairCounter;

所以问题是,如何使用映射比较器定义两对的等价性。我试图连接一对中的两个向量,但这导致 (010,1) == (01,01),这不是我想要的。

struct MyPairComparator
{
    bool operator() (const InputsPair & pair1, const InputsPair pair2) const
    {
        vector<int> itrc1 = pair1.first->inp();
        vector<int> itrc2 = pair1.second->inp();
        vector<int> itrc3 = pair2.first->inp();
        vector<int> itrc4 = pair2.second->inp();
        // ?
        return itrc1 < itrc3;
    }
};

I want to use a map to count pairs of input vectors. If there is a better data structure for this purpose, please tell me.

可以考虑使用 std::unordered_map,原因有两个:

  • 如果正确实施哈希,它可能比 std::map

  • 更快
  • 你只需要实现哈希和 operator== 而不是 operator<,并且 operator== 在这种情况下是微不足道的

有关如何为 std::vector 实现哈希的详细信息,请参见 。在您的情况下,可能的解决方案是将两个向量合并为一个,对其进行排序,然后使用该方法计算哈希值。这是一个简单的解决方案,但会产生许多哈希冲突并导致性能下降。要提出更好的替代方案,需要了解所使用的数据。

据我了解,您想要:

struct MyPairComparator
{
    bool operator() (const InputsPair& lhs, const InputsPair pair2) const
    {
        return std::minmax(std::get<0>(lhs), std::get<1>(lhs))
            < std::minmax(std::get<0>(rhs), std::get<1>(rhs));
    }
};

我们对 {a, b} 进行排序,以便 a < b,然后我们使用常规比较。