1

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?

weeo
  • 2,619
  • 5
  • 20
  • 29

1 Answers1

3

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.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • So maybe I should create the struct containing the key type(in this case string) and struct pointer to the next struct? – weeo Jun 21 '13 at 18:34
  • like this one? http://stackoverflow.com/questions/17223708/hybrid-linked-list-constructed-on-unordered-map/17224096?noredirect=1#17224096 – weeo Jun 21 '13 at 18:35
  • That looks like it should work. As a side note, later in the standard (23.2.5/13), pointers aren't mentioned when talking about what `insert()` does: "The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container". I'm not sure how a reference can be kept valid without the object remaining at the same address, so I think pointers remain valid by inference. – Michael Burr Jun 21 '13 at 18:55