如何在C++中使用map中的计数函数

How to use a count function in map in C++

本文关键字:函数 map C++      更新时间:2023-10-16
#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函数返回什么值?

std::map要求其密钥类型实现严格的弱排序。在普通语言中,您必须能够使用<运算符来比较键。

struct cno a, b;
if (a < b)
// ...

这将不会编译,因为您的键类型上没有定义<运算符。

你有两个选择:

1) 为您的自定义密钥类实现operator<

2) 将第三个可选参数传递给std::map模板,指定一个自定义比较器类。

为了使map<K, V>工作,必须有一个operator <可以比较两个类型为K的对象。这是必要的,因为map是按其密钥排序的。或者,你可以为你的地图提供一个比较器类型

map<K, V, Cmp>