跳到主要内容

std::forward_list swap() 方法

// Non const version only
void swap( forward_list& other ) noexcept(/* see below */);

交换容器的内容与 other 的内容。
不对单个元素调用任何移动、复制或交换操作。

重要

所有迭代器和引用都保持有效。在此操作后,持有此容器的 past-the-end 值的迭代器是否指向此容器还是另一个容器是未指定的。

如果 std::allocator_traits<allocator_type>::propagate_on_container_swap::valuetrue,则使用非成员 swap 的无限定调用来交换分配器。
否则,它们不会被交换。

未定义行为

如果 get_allocator() != other.get_allocator(),则行为是 未定义

.

参数

  • other - 要交换内容的容器

返回值

(无)

复杂度

常数 - O(1)

异常

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

本文源自 此 CppReference 页面。它可能为改进或编辑者的偏好而进行了修改。点击“编辑此页面”可查看对此文档所做的所有更改。
悬停查看原始许可证。

std::forward_list swap() 方法

// Non const version only
void swap( forward_list& other ) noexcept(/* see below */);

交换容器的内容与 other 的内容。
不对单个元素调用任何移动、复制或交换操作。

重要

所有迭代器和引用都保持有效。在此操作后,持有此容器的 past-the-end 值的迭代器是否指向此容器还是另一个容器是未指定的。

如果 std::allocator_traits&lt;allocator_type&gt;::propagate_on_container_swap::valuetrue,则使用非成员 swap 的无限定调用来交换分配器。
否则,它们不会被交换。

未定义行为

如果 get_allocator() != other.get_allocator(),则行为是 未定义

.

参数

  • other - 要交换内容的容器

返回值

(无)

复杂度

常数 - O(1)

异常

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

本文源自 此 CppReference 页面。它可能为改进或编辑者的偏好而进行了修改。点击“编辑此页面”可查看对此文档所做的所有更改。
悬停查看原始许可证。