简体   繁体   中英

Why does unordered_set::begin() change if no rehashing occurs?

Based on reading https://en.cppreference.com/w/cpp/container/unordered_set/emplace , it states: Rehashing occurs only if the new number of elements is greater than max_load_factor()*bucket_count().

In this code:

int main() 
{ 
    unordered_set<int> myset;
    myset.emplace(4);
    cout << myset.bucket_count() << endl;
    cout << myset.max_load_factor() << endl;

    auto it = myset.begin();
    myset.emplace(3);
    cout << (it == myset.begin()) << endl;
}

There is no rehashing when I do emplace the second time (bucket count is 2 and max load factor is 1 right before emplacing the second time, which is not more than the new number of elements, 2), but my begin() iterator changes. Why is this iterator invalidated/changed even though there is no rehashing?

As john already mentioned, your iterator is still valid but it points to the begin() of your unordered_set container at the moment where there was only one element '4'.

So, one thing you should keep in mind using C++ iterators - don't cache them at all. Unless you don't forget to update the iterator every time you do change the container invariants.

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