问题
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