Question: Is it okay in C++ with STL to change a hashmap while iterating over it?

obviously, you can change the iterator variable itself (iter->first and iter->second), but can you:

1. change the value of an existing key which is not necessarily pointed to by the iterator?
2. add new keys?

Answer: 
Quote from [cppreference's docs on `std::unordered_map::operator[]`](http://en.cppreference.com/w/cpp/container/unordered_map/operator_at):

> 
> If an insertion occurs and results in a rehashing of the container, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated.
> 
> 
> 

So changing the values associated with existing keys is okay because no insertion occurs. Inserting explitly with `insert` or by accessing a new key via `operator[]`) is not okay since it can result in a rehashing and invalidate all iterators.

> 
> Obviously, you can change the iterator variable itself (iter->first and iter->second)
> 
> 
> 

That's only partially true. You *can* change the value, but you can't change the key (`iter->first`). This is because `unordered_map<K,V>::value_type = pair<const K, V>`.
From [this `insert` reference`](http://en.cppreference.com/w/cpp/container/unordered_map/insert)

> 
> If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected.
> 
> 
> 

Also:

> 
> Rehashing occurs only if the new number of elements is equal to or greater than max\_load\_factor()\*bucket\_count()
> 
> 
> 

So in some situations it's safe to insert new items, in other it's not. Unless you're certain that your case is safe, it might be best to treat all insertions as unsafe.

On the other hand:

> 
> References are not invalidated
> 
> 
> 

So if you have a reference to a map pair, it's still safe to use.

Since it's only rehashing of keys that can invalidate iterators, changing any data would not cause any problems.