2017-10-12 45 views
1

我有一个类,它看起来像以下:如何在类中包含2d数组时使用类作为映射关键字?

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

现在我想有一个地图,将有提及类作为它的键。

map<A,int> visited; 

如何重载较少的操作符/在这里写一个比较函数,以便地图可以识别重复的二维数组?我在课堂上写了一个overloader。但是,它将包含重复数组的对象视为不同的对象。这是我写的功能:

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; 
} 

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

+0

!=不是<。您的运营商<已损坏。 – 2017-10-12 10:41:01

+0

你能告诉我怎么做吗?我似乎无法找到如何做到这一点。 – arnob1

+0

请注意,'hashmap'标签只能用于[Java的HashMap类](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html) –

回答

2
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。

相关问题