当类包含 2D 数组时,如何将类用作映射的键

How to use a class as a key of a map when the class contains a 2d array?

本文关键字:映射 2D 包含 数组      更新时间:2023-10-16

>我有一个看起来像下面的类:

class A{
   private:
   int *a[10];
};

现在我想要一张地图,它将以提到的类为关键。

map<A,int> visited;

如何在此处重载较少运算符/编写比较函数,以便地图可以识别重复的 2D 数组?我在类中写了一个重载器。但是,它将包含重复数组的对象视为不同的对象。这是我编写的函数:

bool operator<(const A& other) const{
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            if(a[i][j]!=other.a[i][j])return true;
        }
    }
    return false;
 }

我在代码中找不到问题。有人可以帮忙吗?

bool operator<(const A& other) const{
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            if(a[i][j]==other.a[i][j]) continue;
            return a[i][j]<other.a[i][j];
        }
    }
    return false;
}

这应该适用于地图。但如果阵列很大,它可能会很慢。考虑编写哈希函数并使用unordered_map。