交换两个完整的 vectors/queue/stack 时间成本?
Swap two entire vectors/queue/stack time cost?
例如:
v1 = {1,2,3}, v2 = {4,5};
swap(v1, v2);
现在 v1 = {4,5}
、v2 = {1,2,3}
不管这两个向量的长度如何,我认为应该很快吧?只是交换指针?
I think it should be very fast with no regards of the length of these two vectors right?
是的。 std::swap
对于 std::vector
的复杂性由标准保证为常数时间:
23.3.6.3$10,11 [vector.capacity](我加粗):
void swap(vector& x);
Effects: Exchanges the contents and capacity() of *this with that of x.
Complexity: Constant time.
并且 $23.3.6.6/1 [vector.special],std::vector
的 std::swap
专门化为:
template <class T, class Allocator>
void swap(vector<T,Allocator>& x, vector<T,Allocator>& y);
Effects:
x.swap(y);
这里有一些更多的解释:std::vector::swap and std::swap(std::vector)
Exchanges the contents of the container with those of other. Does not
invoke any move, copy, or swap operations on individual elements.
All iterators and references remain valid. The past-the-end iterator is invalidated.
Complexity :
Constant.
It's just swapping pointers?
基本上,它取决于您正在使用的 STL 的实现,但这是实现它的最常见方法。
例如:
v1 = {1,2,3}, v2 = {4,5};
swap(v1, v2);
现在 v1 = {4,5}
、v2 = {1,2,3}
不管这两个向量的长度如何,我认为应该很快吧?只是交换指针?
I think it should be very fast with no regards of the length of these two vectors right?
是的。 std::swap
对于 std::vector
的复杂性由标准保证为常数时间:
23.3.6.3$10,11 [vector.capacity](我加粗):
void swap(vector& x);
Effects: Exchanges the contents and capacity() of *this with that of x.
Complexity: Constant time.
并且 $23.3.6.6/1 [vector.special],std::vector
的 std::swap
专门化为:
template <class T, class Allocator>
void swap(vector<T,Allocator>& x, vector<T,Allocator>& y);
Effects:
x.swap(y);
这里有一些更多的解释:std::vector::swap and std::swap(std::vector)
Exchanges the contents of the container with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.
Complexity : Constant.
It's just swapping pointers?
基本上,它取决于您正在使用的 STL 的实现,但这是实现它的最常见方法。