【问题标题】:How to erase an element in boost unordered_map by local_iterator?如何通过local_iterator擦除boost unordered_map中的元素?
【发布时间】:2019-09-11 01:59:18
【问题描述】:

我正在使用 C++ boost unordered_map 哈希表。 我可以使用local_iterator 来遍历特定的桶。 现在,我想擦除这个桶中的一些元素。

ShmHashMap::local_iterator it = hash_table_->begin(bucket_idx);
while(it != hash_table_->end(bucket_idx)) {
    if(it->second >= now_time) {
        it++;
        continue;
    }
    hash_table_->erase(it);// this usage is not supported
    // although I can `hash_table_->erase(it->first)`, this usage is inefficient
    it++;
}

那么,有没有办法通过local_iterator擦除元素?

【问题讨论】:

    标签: c++ boost hashtable unordered-map


    【解决方案1】:

    假设boost::unordered_map::erasestd::unordered_map::erase的工作方式相同,那么序列:

    hash_table_->erase(it);
    it++;
    

    调用未定义的行为,因为erase 使it 无效。

    你可以这样做:

    it = hash_table_->erase(it);
    

    因为erase 返回删除的迭代器之后的迭代器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多