【问题标题】:How does the STL map::find function work without the equality operator?STL map::find 函数在没有相等运算符的情况下如何工作?
【发布时间】:2010-07-13 19:29:22
【问题描述】:

在底层,STL 映射是一棵红黑树,它使用其键的

map::find() 返回与提供的键匹配的元素(如果存在任何匹配项)

如何在不使用相等运算符的情况下做到这一点?假设我的地图中有键 1、2、3 和 4。仅使用

我什至可以在 /usr/include/c++/4.4.3/bits/stl_tree.h 中看到 find() 只使用用户提供的比较函数:

template<typename _Key, typename _Val, typename _KeyOfValue,
       typename _Compare, typename _Alloc>
typename _Rb_tree<_Key, _Val, _KeyOfValue,
          _Compare, _Alloc>::iterator
_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::
find(const _Key& __k)
{
  iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k);
  return (__j == end()
      || _M_impl._M_key_compare(__k,
                _S_key(__j._M_node))) ? end() : __j;
}

神秘的。如果你能告诉我我的比较函数最终是如何在_M_impl._M_key_compare 中使用而没有明显循环的,那么加分。

【问题讨论】:

    标签: stl map find


    【解决方案1】:

    如果(a &lt; b)false 并且(b &lt; a)false,那么(a == b)。这就是 STL 的 find() 的工作原理。

    【讨论】:

    • 使用类似的逻辑,您可以使用运算符实现 ==、>、>= 和
    【解决方案2】:

    它使用!(a&lt;b) &amp;&amp; !(b&lt;a)

    【讨论】:

    • not (a &lt; b or b &lt; a),保存一个操作。
    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多