简体   繁体   中英

Why does iterating through a map fail in C++?

Consider the following snippet of code:

map<wstring,int>::iterator it;
map<wstring,int> bimap;

//Creating Bigrams out of monograms
for (it= container.begin(); it != container.end();)
{
    bimap[it->first + L" "+((++it)->first)]++;
    ++it;
    ++it;
}

If I run this code the program crashes and the reason for that crash is the second increment of iterator it . Why is it like this? The iterator needs to increment and I am incrementing it twice instead of once! What's wrong with it?

If I want to save two adjacent map item values into some other maps like I am actually doing in the above for statement, how should I go about it? What if I want to combine and store every 3 other items together?

I need to update the iterator to go on respectively, but I have no idea how to do it.

You set your loop to end when you reach the container.end , but because you increment the iterator twice you reach the end, then with that second it++ you try to go further (error).

Example: let's say you have 3 elements.

it = container.begin()

++it // ok
++it //ok

it != container.end() //true

++it // ok BUT AT THIS MOMENT it = container.end !
++it // CRASH

you are incrementing your iterator several times

for (it= container.begin(); it != container.end();)
{
    bimap[it->first + L" "+((++it)->first)]++;  //increment!
    ++it;  //increment!
    ++it;  //increment!
}

so you night be at the last element, enter the loop because it != container.end() condition is met and then go out of bounds.

if you know you will do 2 increments always, but end if there is only one element left, then you might consider this:

for (it= container.begin(); it != container.end();)
{
    //do something
    ++it;  //increment!

    if(it!=container.end()){  //check again. can we move forward?
    //do something
    ++it;  //increment!
    }
}

just increment once on each iteration, and use an auxiliary counter modulo 3 (reset it after each 3 iterations) and do the task you want to do every time it is 0. something like:

int counter_mod3;
for (it= container.begin(); it != container.end();)
{
  if(counter_mod3 == 0) // This zero chooses the phase on which the "sampling" is to be made
    bimap[it->first + L" "+(it->first)]++;  //increment!

  ++it;  //increment!
  counter_mod3 = (counter_mod3++) % 3;
}

If you want to start on other element, instead of the first, just change the phase to 1 or 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM