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.
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
++itr
)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.