跳到主要内容

std::deque swap() 方法

// Non const version only
void swap( deque& 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 <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
本文来源于此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档所做的所有更改。
悬停查看原始许可证。

std::deque swap() 方法

// Non const version only
void swap( deque& 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 <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
本文来源于此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档所做的所有更改。
悬停查看原始许可证。