集合查找中的精确比较
我有一个结构(例如 Foo
),其中包含简单的字符串和一个双精度值,并且我创建了一个集合,其中还有一个比较器类,用于比较这些属性的子集。所以我的声明如下: std::set
当我调用 find()
时,我会期望 Foo
的所有属性用作键还是使用 FooComp
?我假设是前者。
我问的原因是我遇到了一个问题,即使我尝试使用 find()
来检查它的存在,但在集合中未检测到之前添加的对象。我只能假设这已经发生了,因为双倍可能存在细微的差异? double 属性未在比较器中使用,但可能构成键的一部分。
任何想法将不胜感激。
I've got a struct (say Foo
) which contains simply strings and a double and I've created a set which also has a comparator class which compares a subset of those attributes. So my Declaration looks like: std::set<Foo, FooComp>
When I call find()
would I expect all the attributes of Foo
to be used as a key or would FooComp
be used? I'm assuming the former.
The reason that I'm asking is that I've got an issue where an object which has been previously added is not detected in the set even though I've tried using find()
to check it's presence. I can only assume that this has happened as there was a subtle difference in the double perhaps? The double attribute is not used in the comparitor but presumably forms part of the key.
Any thoughts would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
FooComp 需要表示一个二元函数,该函数接受 Foo 的 2 个引用,并确定左边的引用在逻辑上是否小于右边的引用。
并以“严格排序”实现operator(),因此
!FooComp( foo1, foo1 )
FooComp( foo1, foo2 )
=>!FooComp( foo2, foo1 )
FooComp( foo1, foo2 )
&&FooComp( foo2, foo3 )
=>;FooComp( foo1, foo3 )
实际上第一个公理可以从第二个公理推导出来,所以你只需要第二个和第三个公理。
FooComp needs to represent a binary function that takes 2 references to Foo and determines if the left one is logically less than the right one.
and implement operator() with "strict ordering" thus
!FooComp( foo1, foo1 )
FooComp( foo1, foo2 )
=>!FooComp( foo2, foo1 )
FooComp( foo1, foo2 )
&&FooComp( foo2, foo3 )
=>FooComp( foo1, foo3 )
Actually the first axiom can be deduced from the second so you only need the 2nd and 3rd axioms.
std::set::find()
将使用FooComp
,只要 double 不构成该比较的一部分,就应该没问题。std::find
需要operator==
,因此再次取决于您是否定义了它以及它包含的内容,只要它不包含 double (或包含以合理的方式加倍),那么你就很好了。因此,取决于
FooComp
的外观以及您调用的find
...std::set::find()
will useFooComp
, as long as the double does not form part of that comparison, it should be fine.std::find
requiresoperator==
, so again depends if you've define this and what that includes, as long as it does not include the double (or includes the double in a sensible way), then you're good.So, depends what
FooComp
looks like and whichfind
you call...比较器将用于查找集合中的指定项目。
The comparator will be used to find the specified item in the set.
比较类将用于维护
set
的排序以及find()
。The comparison class will be used to maintain the
set
sorted and tofind()
also.