std的怪异行为::多集和上下限

Weird behaviour of std::multiset and upper and lower bounds

本文关键字:上下 std      更新时间:2023-10-16

我正在寻找能够统计std::multiset中元素的不同出现次数的代码。我有以下代码

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

上面的for循环从未停止,我不知道为什么。输出为

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

如果我从上面的代码中删除注释(输入"e"),我会得到类似的输出

3
0
2

在这种情况下,for循环结束了,我也无法理解。

上面的评论引导我找到了解决方案。操作员错了。这是更正后的一个:

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