std :: map的迭代器,允许修改值,但不允许插入/删除

时间:2014-01-12 13:28:28

标签: c++ map iterator const

我对std :: map迭代器行为有疑问。如果我理解正确,std :: map :: const_iterator不允许更改容器中的任何内容,但std :: map :: iterator允许更改it->第二个值键集(即迭代时添加/删除元素等)。在我的情况下,我需要允许更改值,但不允许更改键集。即我需要这样的东西:

std::map<int,int>::iterator it=m.begin()
while(it!=m.end())
{
    ++it->second;  // OK: modifying of values is allowed
    if(it->second==1000)
       m.erase(it++); // Error: modifying the container itself is not allowed
    else
       ++it;
}

似乎标准迭代器不区分更改值和更改容器结构。有没有办法通过实现自定义迭代器来强加这个限制?

1 个答案:

答案 0 :(得分:2)

要修改结构(即插入或删除元素),您需要访问底层容器的实例,而不仅仅是迭代器。

因此,您可以通过向有问题的代码访问迭代器而不是底层容器来实现您所要求的。

template <class Iter> 
cant_remove_if(Iter it, Iter end) { 
    while (it != end) {
        ++it->second; // no problem
        if (it->second==1000)
            // no way to even express the concept `m.erase(it++)` here
        else
            ++begin;
    }
}