1

当我们尝试hash_setSGI 的 STL中删除不存在的密钥时会发生什么?调用是否hash_set::erase首先尝试查找密钥然后删除它?

4

1 回答 1

2

Here is the code used by your implementation of hash_set, it's the erase method of hashtable :

template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::size_type 
hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const key_type& __key)
{
  const size_type __n = _M_bkt_num_key(__key);
  _Node* __first = _M_buckets[__n];
  size_type __erased = 0;

  if (__first) {
    _Node* __cur = __first;
    _Node* __next = __cur->_M_next;
    while (__next) {
      if (_M_equals(_M_get_key(__next->_M_val), __key)) {
        __cur->_M_next = __next->_M_next;
        _M_delete_node(__next);
        __next = __cur->_M_next;
        ++__erased;
        --_M_num_elements;
      }
      else {
        __cur = __next;
        __next = __cur->_M_next;
      }
    }
    if (_M_equals(_M_get_key(__first->_M_val), __key)) {
      _M_buckets[__n] = __first->_M_next;
      _M_delete_node(__first);
      ++__erased;
      --_M_num_elements;
    }
  }
  return __erased;
}

As you can see, it tries to find the key before deleting the node, and does nothing if the key doesn't exist.

Also, from the SGI documentation :

Erase key : Destroys all elements whose key is the same as k, and removes them from a. The return value is the number of elements that were erased, i.e. the old value of a.count(k).

于 2013-05-03T08:27:24.137 回答