Constant Time Swap Logic for Vectors in C++ STL

有些话、适合烂在心里 提交于 2021-02-05 06:47:26

问题


Why is the time complexity required for swapping contents of two C++ STL vectors independent of the size of the corresponding vectors?

Reference: http://www.cplusplus.com/reference/vector/vector/swap/


回答1:


A typical vector implementation stores:

  • The allocator
  • A pointer to the first element
  • A pointer to the past-the-end position, or equivalently, the size
  • A pointer to the end of the memory block owned by the vector, or equivalently, the capacity

swap() simply swaps the pointers, and, if allocator_traits<allocator_type>::propagate_on_container_swap::value is true, the allocator. It doesn't do element-wise swap. In fact, no standard container other than std::array is allowed to do element-wise swap.



来源:https://stackoverflow.com/questions/26219047/constant-time-swap-logic-for-vectors-in-c-stl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!