有没有快速替换两个地图内容的方法?

发布于 2024-12-06 07:16:37 字数 219 浏览 0 评论 0原文

在我的代码中,我有一张地图,其中包含大量数据(~100MB),我需要将所有数据从一张地图复制到另一张地图。目前我正在使用交换但据我了解,交换是一个奇特的方式进行复制。有没有办法简单地转移两个映射所使用的内存?我认为我可以用指针来做到这一点,但我希望有一种更优雅的方式。

In my code I have 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

守护在此方 2024-12-13 07:16:37

ISO/IEC 14882:2011 的 23.2.1 [container.requirements.general] 包含一般容器要求列表。对于所有标准容器,表达式 a.swap(b)swap(a, b) 必须交换 a的内容b 以及除 array 之外的所有标准容器,两者都必须具有恒定时间。这实际上意味着交换地图不能涉及复制所有地图元素。

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.

无边思念无边月 2024-12-13 07:16:37

除非这在分析器运行中作为瓶颈出现,否则您可能会过早进行优化。

我的编译器的 std::map::swap() 有以下注释,这表明映射交换可能非常快:(

  /**
   *  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)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文