我正在使用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
擦除元素?
假设boost::unordered_map::erase
的工作方式与std::unordered_map::erase
相同,那么序列如下:
hash_table_->erase(it);
it++;
调用未定义的行为,因为erase
使it
无效。
但是你可以这样做:
it = hash_table_->erase(it);
因为erase
返回删除后的迭代器。