1

I'm looking for code which counts the different occurences of elements inside a std::multiset. I have following code

#include <set>
#include <iostream>
#include <thread>
#include <chrono>

struct test
{
    std::pair<std::string,std::string> p;
    std::pair<unsigned short, unsigned short> s;
    unsigned short c;
};

bool operator<(test const & l, test const & r)
{
    return (l.p < r.p || l.s < r.s);
}

int main(int argc, char ** argv)
{
    test a = { {"p0","q0"} , {2,4} , 13 };
    test b = { {"p0","q0"} , {2,4} , 26 };
    test c = { {"p0","q0"} , {2,4} , 14 };
    test d = { {"p0","q0"} , {3,5} , 23 };
    //test e = { {"p0","q0"} , {3,5} , 22 };
    test f = { {"p1","q0"} , {2,4} , 13 };

    std::multiset<test> set;
    set.insert(a);
    set.insert(b);
    set.insert(c);
    set.insert(d);
    //set.insert(e);
    set.insert(f);

    for(auto i=set.begin(); i!=set.end(); i=set.upper_bound(*i))
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << set.count(*i) << std::endl;
    }
}

The for loop above does never stop and I don't know why. The output is

3
1
1
1
1
... with endless output of "1"

If I remove comments from code above (put "e" in) I get output like

3
0
2

and in this case the for loop ends which I can't understand either.

Claudio
  • 10,614
  • 4
  • 31
  • 71
user1587451
  • 978
  • 3
  • 15
  • 30

1 Answers1

0

The comments above directed me to the solution. The operator was wrong. Here's the corrected one:

bool operator<(test const & l, test const & r)
{
    if (l.p < r.p)
    {
        return true;
    }
    if (l.p == r.p && l.s < r.s)
    {
        return true;
    }
    return false;
}
user1587451
  • 978
  • 3
  • 15
  • 30