From iterator invalidation rules described at stackoverflow and cppreference, I know that iterator is not invalidated for unordered_map unless rehashing is occurring.
If I use std::vector analogy, then does this means that all the insertion takes place ahead of the location where the iterator is currently pointing too ?
I am modifying the unordered_map on which I am iterating and wanted to make sure that nothing breaks due to iterator invalidation. I am atleast making sure to avoid rehashing using reserve keyword unordered_map reserve
This is the example code that I am writing :
// Function to return vector containing the subvector of inputVector with sum desiredSum, this function returns empty vector if sum not found
std::vector<int> sumVectorFunc(const std::vector<int>& inputVector, const int desiredSum){
std::unordered_map< int,std::vector<int> > sumToSubVector{};
sumToSubVector.reserve(desiredSum+1);
// initialization with the zero sum
sumToSubVector[0] = std::vector<int>{};
for(auto itVector : inputVector){ // iterate over the vector of elements
std::unordered_set<int> numbersAddedThisCycle{};
for(auto itSubVectors : sumToSubVector){ // iterate over constructed subVectors
auto sum = itVector + itSubVectors.first;
//the new sum constructed by adding this new vector element is not yet found and make sure that you are not adding the same element again and again to get new numbers
if(sumToSubVector.find(sum) == sumToSubVector.end() && numbersAddedThisCycle.find(sum) == numbersAddedThisCycle.end()){
sumToSubVector[sum] = itSubVectors.second;
sumToSubVector[sum].push_back(itVector);
numbersAddedThisCycle.insert(sum);
}
}
}
// for(auto it : sumToSubVector){
// std::cout<<"FOr sum "<<it.first<<", we need the elements : ";
// for(auto it2 : it.second){
// std::cout<<it2<<" ";
// }std::cout<<"\n";
// }
return sumToSubVector[desiredSum];
}
I believe that this particular implementation will not break even if the insertion will happen before the iterator position (i.e. the loop will not be iterating through the element inserted in that particular insertion cycle)
To sum up the question: Where is the insertion happening ? How will my loop behave to this insertion? Even if the iterators are not invalidated, the unordered_map
on which the range for is iterating is clearly changed, how will this affect the loop? Could the inserted elements be skipped in the range for or not?