views:

51

answers:

2

I have a hashmap which contains items of struct Foo (not pointers). Now, I want to have pointers of those items in a list. How can I do this?

I have tried to iterate the hashmap and insert the &*iter's to the list but the pointers get invalidated as soon as they are out of scope.

I should be able to do this without dynamic allocation, shouldn't I?

I do like this and it does not work: for(...) { Foo& bar = *iter; list.insert(&bar); }

+1  A: 

Pointers to items in the hashmap will become invalid the same time iterators become invalid.

If you leave the hashmap alone (i.e. don't insert/delete/copy/anything after you have iterated it and taken addresses of its elements), your pointers should remain valid.

Matt Curtis
I leave it alone but it does not help
Kiity
Assuming `hash_map` (from the STL) or `unordered_map` (from C++0x) is being used, then iterators are not invalidated when elements are added to or removed from the container (except that when removing an element, any iterators to that element are invalidated, obviously).
James McNellis
@James Agree but Kitty doesn't say what the implementation is (though any implementation could reasonably be expected to have the same properties).
Matt Curtis
Check out my edit
Kiity
A: 

I have a hashmap which contains items of struct Foo (not pointers). Now, I want to have pointers of those items in a list. How can I do this?

Like this:

typedef Whatever_Hash_Map<Foo> Container;
Container container;
...populate container...
std::list<Foo*> l;
for (Container::const_iterator i = container.begin(); i != container.end(); ++i)
    l.insert(&*i);
...use list...

I have tried to iterate the hashmap and insert the &*iter's to the list but the pointers get invalidated as soon as they are out of scope.

You can't use this list if you let anything go out of scope. If you need the list to persist past the return of the function that creates it, be sure to allocate the list itself on the heap and return a pointer to it.

I should be able to do this without dynamic allocation, shouldn't I?

A list allocates nodes dynamically. The Hash Map probably internally allocates buckets dynamically. But, you don't have to explicitly allocate pointers-to-Foos dynamically - all the Standard and similar containers would copy the Foos onto the heap using value semantics (i.e. Foo's copy constructor or assignment operator).

I do like this and it does not work: for(...) { Foo& bar = *iter; list.insert(&bar); }

That in and of itself looks fine, the error is elsewhere in your code. That's why you should follow James' suggestion and post enough code that we can point out your error.

Tony