开发者

Is there a fast way to replace two map contents?

开发者 https://www.devze.com 2023-04-06 11:06 出处:网络
In my code I h开发者_运维知识库ave a map which holds a large amount of data (~100MB) I need to copy all that data from one map to another. currently I am doing this with swap but to my understanding,

In my code I h开发者_运维知识库ave a map which holds a large amount of data (~100MB) I need to copy all that data from one map to another. currently I am doing this with swap but to my understanding, swap is a fancy way to do a copy. Is there a way to simply transfer the memory used by the two maps? I think that I can do this with pointers but I was hoping for a more elegant way.


23.2.1 [container.requirements.general] of ISO/IEC 14882:2011 contains a list of general container requirements. For all standard containers the expressions a.swap(b) and swap(a, b) must exchange the contents of a and b and for all standard containers other than array both must have constant time. This effectively means that swapping maps cannot involve copying all the map elements.


Unless this came up in a profiler run as a bottleneck, you may be optimizing prematurely.

My compiler's std::map::swap() has the following comment, which indicates that a map swap is likely to be very fast:

  /**
   *  This exchanges the elements between two maps in constant
   *  time.  (It is only swapping a pointer, an integer, and an
   *  instance of the @c Compare type (which itself is often
   *  stateless and empty), so it should be quite fast.)  Note
   *  that the global std::swap() function is specialized such
   *  that std::swap(m1,m2) will feed to this function.
   */

(g++ 4.4.5)

0

精彩评论

暂无评论...
验证码 换一张
取 消