如何通过local_iterator擦除boost unordered_map中的元素?

问题描述 投票:0回答:1

我正在使用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个回答
1
投票

假设boost::unordered_map::erase的工作方式与std::unordered_map::erase相同,那么序列如下:

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

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

但是你可以这样做:

it = hash_table_->erase(it);

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

© www.soinside.com 2019 - 2024. All rights reserved.