prateek behera
prateek behera

Reputation: 11

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;   
}

In this code while searching for a struct variable k by using count i get this error.

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

How can we use the count function in C++?What values do count function return?

Upvotes: 1

Views: 484

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

In order for map<K, V> to work, there must be an operator < that can compare two objects of type K. This is necessary because a map is ordered by its keys. You can, alternatively, supply a comparator type to your map

map<K, V, Cmp>

Upvotes: 3

Sam Varshavchik
Sam Varshavchik

Reputation: 118310

A std::map requires that it's key type implements strict weak ordering. In plain language, you have to have the ability to compare keys using the < operator.

struct cno a, b;

if (a < b)
  // ...

This will not compile because you do not have the < operator defined on your key type.

You have two options:

1) Implement operator< for your custom key class.

2) Pass the third optional parameter to the std::map template, specifying a custom comparator class.

Upvotes: 3

Related Questions