如何在C++中使用map中的计数函数
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函数返回什么值?
std::map
要求其密钥类型实现严格的弱排序。在普通语言中,您必须能够使用<
运算符来比较键。
struct cno a, b;
if (a < b)
// ...
这将不会编译,因为您的键类型上没有定义<
运算符。
你有两个选择:
1) 为您的自定义密钥类实现operator<
。
2) 将第三个可选参数传递给std::map
模板,指定一个自定义比较器类。
为了使map<K, V>
工作,必须有一个operator <
可以比较两个类型为K
的对象。这是必要的,因为map
是按其密钥排序的。或者,你可以为你的地图提供一个比较器类型
map<K, V, Cmp>
相关文章:
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 如何创建一个模板化函数,可以在任何具有字符串键的 std::map 上运行?
- 在C++中实现类似 python "map"函数的问题:调用类成员函数
- 通过构造函数插入 std::map
- 如何将不同的函数签名映射到同一个 std::map?
- 如何在 Visual C++ 中从返回类型为 map 的函数返回 null?
- 为什么 STL 函数使用节点的颜色来计算 std::map 节点前身
- 为什么std::map有find成员函数
- 在构造函数初始值设定项中使用 Map 的初始值设定项列表
- 尝试在 std::map 中插入抽象类时没有用于调用的匹配函数
- 有没有类似的函数,比如 c++ 中的 JS Array.prototype.map?
- 在 std::map 中插入对象时构造函数中变量的地址
- std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数
- 为什么我可以将 std::map 的键传递给一个期望非常量的函数?
- 正确的友元定义,以授予 std::map 对私有默认构造函数的访问权限
- 如何在搜索中不使用std::map的自定义比较函数(map::find)