2017-10-12 42 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。

相關問題