3

I'm trying to write a program that is taking 1000 random numbers from 0 to 9 and then counting how many times each number appeared:

    srand(time(NULL));
    multiset<int> M;//multiset that contains 1000 random numbers from 0 to 9
    for (int i = 0; i < 1000; i++){
        r.insert(rand() % 10);
        s.insert(rand() % 10);
    }

    vector <int> R(10);//vector that stores how many times each number appeared 
    //(so R[0] equals how many times 0 appeared and so on)

    pair<multiset<int>::iterator, multiset<int>::iterator> zero = M.equal_range(0);
    R[0] = zero.second - zero.first;

The problem is in the last line (in which I'm trying to count the number of times 0 appeared), it underlines minus and says that no operator matches these operands. But why? Aren't zero.first and zero.second ends of compartments? And how to fix it?

Edit: I have to use a multiset, vector and equal_range, these are the things my teacher picked, not me.

Ania
  • 450
  • 4
  • 14

2 Answers2

4

Use distance(zero.first, zero.second). The - operator cannot be applied to multiset iterators.

David G
  • 94,763
  • 41
  • 167
  • 253
drbombe
  • 609
  • 7
  • 15
-1

This would be far easier using a map:

std::map<int, int> counts;
...
count[num]++; // map::operator[] will insert the value if it's not already in the sequence.
SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
  • 1
    "this would be easier using [...]" does not answer the questions provided – Fureeish Dec 18 '17 at 21:06
  • alternatives to a poor or suboptimal approach can complement an already complete answer. unfortunately this is not complete – Ankur S Jun 21 '18 at 12:48