std::vector::swap 是如何实现的? [英] How is std::vector::swap implemented?
问题描述
我想到将数组从一个 std::vector
复制到另一个的最快方法是交换它们的指针,只要你不再关心你的向量正在交换.所以我去寻找并找到了std::vector::swap
.我假设交换指针是它的实现方式,但我没有在参考资料中看到解释.
It occurred to me that the fastest way to copy the array from one std::vector
to another would be to swap their pointers, as long as you don't care anymore about the vector you are swapping from. So I went looking and found std::vector::swap
. I assume that swapping pointers is how its implemented, but I didn't see an explanation in the reference.
推荐答案
一个简化的、最小的向量实现可能有如下成员来管理向量中的数据:
A simplified, minimal vector implementation might have something like the following members to manage the data in the vector:
template <typename T>
class simple_vector
{
public:
// ...
static
void swap(simple_vector<T>& x, simple_vector<T>& y);
private:
T* elements; // a pointer to the block of memory holding the elements in the vector
size_t count; // number of 'active' elements
size_t allocated; // number of elements allocated (not all of which are necessarily used at the moment)
};
swap()
操作只会交换每个简化向量的胆量",将所有动态分配的缓冲区(以及其中包含的元素)留在原位.只有指向那些动态分配的指针才会移动:
A swap()
operation would just swap the 'guts' of each simplified_vector, leaving all of the dynamically allocated buffers (and the elements contained in them) in place. Only the pointers to those dynamic allocations get move around:
template <typename T>
void simple_vector<T>::swap(simple_vector<T>& x, simple_vector<T>& y)
{
T* tmp_elements = x.elements;
size_t tmp_count = x.count;
size_t tmp_allocated = x.allocated;
x.elements = y.elements;
x.count = y.count;
x.allocated = y.allocated;
y.elements = tmp_elements;
y.count = tmp_count;
y.allocated = tmp_allocated;
}
请注意,实际的 std::vector
实现可能使用与这个简单示例不完全相同的技术(例如移动构造临时对象),但我认为它传达了一般概念.
Note that the actual std::vector
implementation might use techniques that aren't exactly the same (such as move constructing a temporary) as this simple example, but I think it conveys the general concept.
这篇关于std::vector::swap 是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!