c++c++11stlunordered-multiset

how to end a loop at a particular time in unordered_multiset


Good morning,

I am trying for a loop when a particular condition is met in an unordered_multiset with the end operation. But it does not work and I get a Segmentation fault in the next iteration of the loop.

Code:

std::unordered_multiset<Element, ElementHash>::iterator itr;
Element elementTemp1("");
for (itr = almacen.begin(); itr != almacen.end(); ++itr) {
    Element tmp(*itr);
    if(tmp.getNombre() == "prueba"){
       itr = almacen.end();
    }
}

How can I solve it? Or maybe my structure is not the right one.


Solution

  • What about this:

    unordered_multiset<Element, ElementHash> :: iterator itr;
    Element elementTemp1("");
    for (itr = almacen.begin(); itr != almacen.end(); ++itr) {
    Element tmp(*itr);
        if(tmp.getNombre == "prueba"){
           break;
        }
    }
    

    The break stops the execution of the for loop at that point. Is that what you want?

    As mentioned by Sneftel in the comment: Your program crashes because a for-loop is executed in a way that after each iteration

    1. The increment/change operation gets executed (in your code: ++itr)
    2. The check is performed whether the loop is executed another time (in your code: itr != almacen.end()

    But when you set the iterator within your loop already to almacen.end() you cannot increment it any further. But that is what happens after that iteration of the loop with Step 1 I described. And there your program crashes.