簡體   English   中英

如何在C ++中的地圖中使用計數功能

[英]How to use a count function in map in C++

#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時出現此錯誤。

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

如何在C ++中使用count函數?count函數返回什么值?

一個std::map要求它的鍵類型實現嚴格的弱排序 用簡單的語言,您必須能夠使用<運算符比較鍵。

struct cno a, b;

if (a < b)
  // ...

這不會編譯,因為您沒有在鍵類型上定義<運算符。

您有兩種選擇:

1)為您的自定義鍵類實現operator<

2)將第三個可選參數傳遞給std::map模板,指定一個自定義比較器類。

為了使map<K, V>工作,必須有一個operator < ,可以比較兩個類型為K對象。 這是必需的,因為map是通過其鍵排序的。 您也可以為地圖提供比較器類型

map<K, V, Cmp>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM