std::deque swap() 方法
- 自 C++17 起
- C++17 之前
// Non const version only
void swap( deque& other ) noexcept(/* see below */);
// Non const version only
void swap( deque& other );
将容器的内容与 `other` 的内容进行交换。不调用单个元素的任何移动、复制或交换操作。
失效
past-the-end 迭代器失效。
所有迭代器和引用保持有效。
- 自 C++11 起
如果 std::allocator_traits<allocator_type>::propagate_on_container_swap::value
为 true
,则使用非限定调用非成员 swap()
交换分配器。
否则,它们不会被交换(如果 get_allocator() != other.get_allocator()
,则行为未定义
参数
other
- 要交换内容的容器
返回值
(无)
复杂度
常数 - O(1)。
异常
- 自 C++17 起
- C++17 之前
noexcept(std::allocator_traits<Allocator>::is_always_equal::value)
(无)
示例
Main.cpp
#include <iostream>
#include <deque>
template<class Os, class Co> Os& operator<<(Os& os, const Co& co) {
os << "{";
for (auto const& i : co) { os << ' ' << i; }
return os << " } ";
}
int main()
{
std::deque<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';
// Note that after swap the iterators and references stay associated with their
// original elements, e.g. it1 that pointed to an element in 'a1' with value 2
// still points to the same element, though this element was moved into 'a2'.
}
可能输出
{ 1 2 3 } { 4 5 } 2 5 1 4
{ 4 5 } { 1 2 3 } 2 5 1 4