C++: Copying hashmap contents to pointer list
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开发者_JAVA技巧: for(...) { Foo& bar = *iter; list.insert(&bar); }
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.
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.
精彩评论