2

How could I create a copy of an unordered_map from an existing one? Could I use assignment operator or I need to iterate it one by one? Also, I am using shared_ptr as the value in the map. Did I need to take extra care because it is shared_ptr?

typedef unordered_map<string, shared_ptr<classA>>MAP1;
MAP1 map1;
map1["abc"] = make_shared<classA>();
MAP2 map2 = map1; ?? //can I use assignment operator??

Thanks.

Leslieg
  • 877
  • 1
  • 7
  • 4
  • 9
    I don't usually answer in this fashion, but did you try it? – GManNickG Jan 12 '11 at 06:00
  • this is not an assignment, as much as it looks like it. It is in fact a call to the constructor of MAP2... but nobody here knows what `MAP2` is so we'll have a hard time answering your question. And really you should refrain from using all-caps identifiers, they are usually reserved for macros. – Matthieu M. Jan 12 '11 at 07:38
  • I think [you mean the Standard Template Library](http://stackoverflow.com/a/5205571/834176). – Keith Pinson Dec 17 '12 at 23:13

2 Answers2

3

Yes you can.

Regarding shared_ptr, if you want the copied pointers to point to the same values then no. If you want two separate copy (deep copy), then you need to do the copying yourself.

Dat Chu
  • 10,822
  • 13
  • 58
  • 82
1

See: MSDN std::unordered_map::operator=

The contents of map2 are first removed, then the contents of map1 will be copied and placed into map2. I don't see a problem with having a shared_ptr in there.

helloworld922
  • 10,801
  • 5
  • 48
  • 85