std::map<std::string, int> map;
map["a"] = 1;
int times = 0;
for (auto i = map.begin(), e = map.end(); i != e;) {
auto current = i++;
times++;
if (current->first == "a") map.insert(std::pair<std::string, int>("c", 3));
}
std::cout << times << std::endl; //prints 1.
The for loop loops only once but it has to loop twice, because I added one more pair to map. How do I update iterator every loop if an pair is added or removed?
Thanks :).
> The for loop loops only once but it has to loop twice, because I added one more pair to map.
It will iterate over the newly added item only if that item appears in the ordered sequence after the current item that is being iterated over. (This is guaranteed only if we haven't prematurely advanced the iterator before the insertion was done.)
If that item appears before the current item that is being iterated over, it will not be encountered as the iteration progresses forward from the current item.
for (auto i = map.begin(); i != map.end(); i++) {
map.insert(std::pair<std::string, int>("something", 5));
//i->something (maybe remove or add new pair).
//only future pairs will be added or removed.
i = map.updateIterator(); //to update iterator
}
If the intent is that the inserted items should also be processed, then:
if the inserted item would appear before the current item in the sorted sequence, we would need to process it separately if it is not to be missed (perhaps process it immediately after its insertion).
if the inserted item would appear after the current item in the sorted sequence, we do not need to do anything special; it would be encountered normally as the iteration progresses.
¿update how? ¿what do you want to happen/not happen?
To just initialize new pairs from map to iterator. For future elements that are going to listed. For example (my real code):
1 2 3 4 5 6 7 8 9 10
for (auto i = listeners_[event->type].begin(), e = listeners_[event->type].end(); i != e;) {
auto current = i++;
current->second(event); //Calls the listener function. Adds new elements to buffer container
updateEvents(); //adds elements from buffer container to container.
//Problem is here. It adds new pairs to container but iterator doesn't list them.
}
One thing that you need to be very very clear on: it's often invalid to update a container while you're iterating over it. You're lucky here because map<> is one of the most forgiving of the containers. The lesson is to be sure you understand how an iterator behaves when you modify the container.
If you need to Do Something with the newly inserted items, then you might need to make two passes:
1 2 3 4 5 6 7 8 9
for( auto iter = map.begin(); iter != map.end(); ++iter ) {
if (some condition) {
insert new item in a DIFFERENT map
}
}
for( auto iter = differentMap.begin(); iter != differentMapap.end(); ++iter ) {
map[iter->first] = iter->second;
Do Something
}
This way you can get around the fact that the new item might appear before the current iterator.