std::forward_list swap() 方法
- 自 C++17 起
- 自 C++11 起
// Non const version only
void swap( forward_list& other ) noexcept(/* see below */);
// Non const version only
void swap( forward_list& 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 <forward_list>
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::forward_list<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