我对 std::map 迭代器行为有疑问。如果我理解正确, std::map::const_iterator 不允许更改容器中的任何内容,但 std::map::iterator 允许更改 it->第二个值 和 键集(即迭代时添加/删除元素等)。在我的情况下,我需要允许更改值,但不允许更改键集。 IE。我需要这样的东西:
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;
}
标准迭代器似乎不区分更改值和更改容器结构。有没有办法通过实现自定义迭代器来施加此限制?
最佳答案
要修改结构(即插入或删除元素),您需要访问底层容器的实例,而不仅仅是迭代器。
因此,您可以通过仅允许相关代码访问迭代器而不是底层容器来实现您的要求。
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;
}
}
关于c++ - std::map 的迭代器允许修改值,但不允许插入/删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21075185/