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

标签 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++ 中的计数函数?计数函数返回什么值?

最佳答案

A std::map要求它的键类型实现 strict weak ordering .用通俗易懂的语言,您必须能够使用 < 来比较键。运营商。

struct cno a, b;

if (a < b)
  // ...

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

你有两个选择:

1) 实现 operator<用于您的自定义键类。

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

关于c++ - 如何在 C++ 中的 map 中使用计数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37481980/

相关文章:

c++ - 在模板中使用 typedef 和 typename

C++11 正则表达式多行 : Why does the group ([^\\0]+\n)? some_text 在 match[1] 中包含所有内容?

c++ - 如何将数组索引存储在映射中

c++ - 避免模​​偏差的快速方法

c++ - 简单的 C++ 程序超出其数组边界并崩溃

c++ - 在成员函数中的析构函数之后调用构造函数

c++ - 使用 lambda 简化容器迭代

c++ - VTK:如何为柏拉图式立体着色

c++ - 禁止访问 C++ 中的基类句柄

c++ - 防止存储在内存中的字符串被其他程序读取