weeo
weeo

Reputation: 2819

will unordered_map iterator change?

Hi I wonder if the iterator will change if the size of the unordered_map changes and then rehashed? I'm trying to create a struct of iterator pointers to bring several elements in the unordered_map together.

#include<string>
#include<tr1/unordered_map>

struct linker
{
    unordered_map<Key,T>::iterator it;
    unordered_map<Key,T>::iterator it1;
    unordered_map<Key,T>::iterator it2;

};

unordered_map<string,int> map({{"aaa",1},{"bbb",2},{"ccc",3},{"ddd",4}});

linker node1 = new linker;
node1.it = map.find("aaa");
node1.it1 = &map.find("ccc");
node1.it2 = &map.find("ddd");

map.insert(make_pair({"sss",23}));
.....

after insert too many elements, will the iterator pointer still available and point to the same element/key before the map size changes?

Upvotes: 1

Views: 1971

Answers (1)

Michael Burr
Michael Burr

Reputation: 340436

C++11 23.2.5/8 "Unordered associative containers":

Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements.

So the iterators would be invalidated on a rehash, but you could take references to the elements instead.

Upvotes: 3

Related Questions