std::vector<T,Allocator>:: swap
|
void
swap
(
vector
&
other
)
;
|
(C++17 前) | |
|
void
swap
(
vector
&
other
)
noexcept
(
/* see below */
)
;
|
(C++17 起)
(C++20 起为 constexpr) |
|
将容器的内容与容量与 other 进行交换。不会对单个元素执行任何移动、复制或交换操作。
所有迭代器和引用保持有效。
end()
迭代器会失效。
|
若
std::
allocator_traits
<
allocator_type
>
::
propagate_on_container_swap
::
value
为
true
,则通过非限定调用非成员函数
|
(since C++11) |
目录 |
参数
| 其他 | - | 用于交换内容的容器 |
异常
|
(无) |
(C++17 前) |
|
noexcept
规范:
noexcept
(
std::
allocator_traits
<
Allocator
>
::
propagate_on_container_swap
::
value
|| std:: allocator_traits < Allocator > :: is_always_equal :: value ) |
(C++17 起) |
复杂度
常量。
示例
#include <iostream> #include <vector> template<class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << '{'; for (const auto& i : co) os << ' ' << i; return os << " } "; } int main() { std::vector<int> a1{1, 2, 3}, a2{4, 5}; auto it1 = std::next(a1.begin()); auto it2 = std::next(a2.begin()); int& ref1 = a1.front(); int& ref2 = a2.front(); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; a1.swap(a2); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; // 注意交换后迭代器和引用仍与其原始元素保持关联,例如 it1 原本指向 a1 中值为 2 的元素, // 交换后仍指向同一元素,尽管该元素已被移至 a2 中。 }
输出:
{ 1 2 3 } { 4 5 } 2 5 1 4
{ 4 5 } { 1 2 3 } 2 5 1 4
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用范围 | 发布时行为 | 正确行为 |
|---|---|---|---|
| LWG 341 | C++98 |
std::vector
的容量无法交换
|
容量也会被交换 |
参见
|
特化
std::swap
算法
(函数模板) |