I have code that looks like the below:
std::unordered_set<int> ht{1,2,3};
ht.reserve(10000); // ht will not exceed this size
for(int i = 0; i < n; i++)
{
auto j = i;
for(auto it = ht.begin(); it != ht.end(); ++it)
{
// do some stuff
int v = j++;
ht.emplace(v);
}
}
For the inner loop, I want to loop from the beginning of ht to the end, but I don't want the loop to go over any of the newly added elements within the loop. In other words, is the above equivalent to the below?
std::unordered_set<int> ht{1,2,3};
ht.reserve(10000); // ht will not exceed this size
for(int i = 0; i < n; i++)
{
auto temp = ht;
auto j = i;
for(auto it = ht.begin(); it != ht.end(); ++it)
{
// do some stuff
auto v = j++;
temp.emplace(j);
}
ht = temp;
}
Based on a few runs that I did, it seems to be equivalent, but I don't know if this is undefined behavior, or if they are indeed equivalent. If the unordered_set
was changed to a vector
, this would not work, but it seems the forward iterators work.
Does the answer change if the ht.reserve(10000); // ht will not exceed this size
was not present or if ht
did in fact exceed the reserved capacity, and therefore all the forward iterators will be invalidated?