std的怪异行为::多集和上下限
Weird behaviour of std::multiset and upper and lower bounds
我正在寻找能够统计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;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- constexpr上下文中std::initializer_list的验证
- std::constexpr 上下文中的可选赋值运算符
- 在c++std::函数的上下文中无效使用void表达式
- 在 C++11 上下文中使用 std::可选
- 即使在多核上下文中,是否有任何 std::chrono 线程安全保证
- std::数组指针在constexpr上下文中的Size()