跳到主要内容

std::stack swap()

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

将容器适配器的内容与 other 的内容进行交换。

注意

有效执行

using std::swap;
swap(c, other.c);

参数

  • other - 用于交换内容的容器适配器

返回值

(无)

异常

noexcept 规范

noexcept(std::is_nothrow_swappable_v<Container>)

复杂度

等同于底层容器的 swap

注意

对于标准容器,复杂度保证为

  • 容器大小的线性复杂度 - O(size()),适用于 std::array
  • 常量 - O(1),适用于所有其他容器。

备注

一些实现(例如 libc++)提供 swap 成员函数作为 C++11 之前模式的扩展。

示例

Main.cpp
#include <iostream>
#include <stack>
#include <string>
#include <vector>

template <typename Stack>
void print(Stack stack /* pass by value */, int id)
{
std::cout << "s" << id << " [" << stack.size() << "]: ";
for (; !stack.empty(); stack.pop())
std::cout << stack.top() << ' ';
std::cout << (id > 1 ? "\n\n" : "\n");
}

int main()
{
std::vector<std::string>
v1{"1","2","3","4"},
v2{"Ɐ","B","Ɔ","D","Ǝ"};

std::stack s1{std::move(v1)};
std::stack s2{std::move(v2)};

print(s1, 1);
print(s2, 2);

s1.swap(s2);

print(s1, 1);
print(s2, 2);
}
输出
s1 [4]: 4 3 2 1 
s2 [5]: Ǝ D Ɔ B Ɐ

s1 [5]: Ǝ D Ɔ B Ɐ
s2 [4]: 4 3 2 1

std::stack swap()

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

将容器适配器的内容与 other 的内容进行交换。

注意

有效执行

using std::swap;
swap(c, other.c);

参数

  • other - 用于交换内容的容器适配器

返回值

(无)

异常

noexcept 规范

noexcept(std::is_nothrow_swappable_v<Container>)

复杂度

等同于底层容器的 swap

注意

对于标准容器,复杂度保证为

  • 容器大小的线性复杂度 - O(size()),适用于 std::array
  • 常量 - O(1),适用于所有其他容器。

备注

一些实现(例如 libc++)提供 swap 成员函数作为 C++11 之前模式的扩展。

示例

Main.cpp
#include <iostream>
#include <stack>
#include <string>
#include <vector>

template <typename Stack>
void print(Stack stack /* pass by value */, int id)
{
std::cout << "s" << id << " [" << stack.size() << "]: ";
for (; !stack.empty(); stack.pop())
std::cout << stack.top() << ' ';
std::cout << (id > 1 ? "\n\n" : "\n");
}

int main()
{
std::vector<std::string>
v1{"1","2","3","4"},
v2{"Ɐ","B","Ɔ","D","Ǝ"};

std::stack s1{std::move(v1)};
std::stack s2{std::move(v2)};

print(s1, 1);
print(s2, 2);

s1.swap(s2);

print(s1, 1);
print(s2, 2);
}
输出
s1 [4]: 4 3 2 1 
s2 [5]: Ǝ D Ɔ B Ɐ

s1 [5]: Ǝ D Ɔ B Ɐ
s2 [4]: 4 3 2 1