【问题标题】:How to use a class as a key of a map when the class contains a 2d array?当类包含二维数组时,如何使用类作为地图的键?
【发布时间】:2017-10-12 10:06:35
【问题描述】:

我有一个如下所示的类:

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

现在我想要一张地图,其中提到的类是关键。

map<A,int> visited;

如何重载 less 运算符/在此处编写比较函数,以便地图可以识别重复的 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;
 }

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

【问题讨论】:

  • != 不是 <.>
  • 那你能告诉我怎么做吗?我似乎找不到任何方法来做到这一点。
  • 请注意hashmap标签只能用于Java's HashMap class

标签: c++ multidimensional-array hashmap c++14


【解决方案1】:
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。

【讨论】:

    猜你喜欢
    • 2020-12-20
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2019-12-31
    相关资源
    最近更新 更多