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.