2016-05-27 8 views
1
#include<iostream> 
#include<algorithm> 
#include<cstdio> 
#include<map> 
#include<vector> 
using namespace std; 
struct cno{ 
    int sub[5]; 
}; 
int main() 
{ 
    int n; 
    map<cno,int> s; 
    int maxN = -1; 
    struct cno k; 
    while(scanf("%d",&n) && n){ 
     for(int i = 0;i<5;i++){ 
      cin>>k.sub[i]; 
     } 
     if(!s.count(k)){ //Error in this line. 
      s[k] = 1; 
      maxN = max(maxN,1); 
     } 
     else{ 
      int m = s[k] + 1; 
      s[k] = m; 
      maxN = max(maxN,m); 
     } 
    } 
    return 0; 
} 

このコードでは、countを使用して構造体変数kを検索するときにこのエラーが発生します。C++でmap内のcount関数を使用する方法

‘const cno’ is not derived from ‘const std::reverse_iterator<_Iterator>’ 
     { return __x < __y; } 

C++でカウント関数を使用するにはどうすればよいですか?カウント関数はどのような値を返しますか?

+0

[これは役立ちますか](http://en.cppreference.com/w/cpp/container/map/count)? –

答えて

3

std::mapのキータイプはstrict weak orderingであることが必要です。単純な言葉では、<演算子を使用してキーを比較する能力が必要です。

struct cno a, b; 

if (a < b) 
    // ... 

あなたのキータイプに定義された<演算子を持っていないので、これはコンパイルされません。

1)カスタムキークラスのoperator<を実装します。

は、2つのオプションがあります。

2)カスタムコンパレータクラスを指定して、std::mapテンプレートに3番目のオプションパラメータを渡します。

3

map<K, V>を動作させるには、タイプKの2つのオブジェクトを比較できるoperator <が必要です。これは、mapがそのキーによって順序付けされているために必要です。代わりに、マップにコンパレータタイプを指定することもできます。

map<K, V, Cmp> 
+0

あなたの答えはArmenありがとうございます。コンパレータ機能を書く方法を説明できますか?私は、構造変数の昇順で要素をソートする必要があります。 –

関連する問題