bkxp
bkxp

Reputation: 1145

iterator for std::map that allows modification of values, but not insertion/deletion

I have a question about the std::map iterator behavior. If I understand it correctly, the std::map::const_iterator does not allow to change anything in the container, but std::map::iterator allows to both change the it->second values and the key set (i.e. adding/deleting elements while iterating, etc.). In my situation I need to allow changing the values, but not the key set. I.e. I need something like this:

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;
}

It seems like the standard iterators do not distinguish between changing the values and changing the container structure. Is there a way to impose this restriction by implementing a custom iterator?

Upvotes: 2

Views: 3090

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490158

To modify the structure (i.e., insert or delete elements) you need access to an instance of the underlying container, not just an iterator.

Therefore, you can achieve what you're asking for by giving the code in question access only to the iterator, not the underlying container.

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;
    }
}

Upvotes: 2

Related Questions