C ++ STL中向量的恒定时间交换逻辑 [英] Constant Time Swap Logic for Vectors in C++ STL

查看:46
本文介绍了C ++ STL中向量的恒定时间交换逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么交换两个C ++ STL向量的内容而不需要相应向量大小的时间复杂性为何?

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

参考: http://www.cplusplus.com/reference/vector/vector/swap/

推荐答案

典型的矢量实现存储:

  • 分配器
  • 指向第一个元素的指针
  • 指向末尾位置或大小的指针
  • 指向向量所拥有的存储块末尾的指针,或等效地为容量

swap()仅交换指针,如果 allocator_traits< allocator_type> :: propagate_on_container_swap :: value 为true,则分配器.它不执行逐元素交换.实际上,除 std :: array 之外,没有标准容器可以进行按元素的交换.

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.

这篇关于C ++ STL中向量的恒定时间交换逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆