std::stack<T,Container>:: swap
From cppreference.net
|
void
swap
(
stack
&
other
)
noexcept
(
/* see below */
)
;
|
(自 C++11 起) | |
other
. Effectively calls
using std::swap; swap(c, other.c);
目录 |
参数
| 其他 | - | 用于交换内容的容器适配器 |
返回值
(无)
异常
|
noexcept
规范:
noexcept
(
noexcept
(
swap
(
c, other.
c
)
)
)
上述表达式中,标识符
|
(C++11 起)
(C++17 前) |
|
noexcept
规范:
noexcept
(
std::
is_nothrow_swappable_v
<
Container
>
)
|
(C++17 起) |
复杂度
与底层容器相同(通常为常量)。
注释
某些实现(例如 libc++)在 C++11 之前的模式中作为扩展提供了
swap
成员函数。
示例
运行此代码
#include <iostream> #include <concepts> #include <stack> #include <string> #include <string_view> #include <vector> template<typename Adaptor> requires (std::ranges::input_range<typename Adaptor::container_type>) void print(std::string_view name, const Adaptor& adaptor) { struct Printer : Adaptor // 用于访问受保护的 Adaptor::Container c; { void print(std::string_view name) const { std::cout << name << " [" << std::size(this->c) << "]: "; for (auto const& elem : this->c) std::cout << elem << ' '; std::cout << '\n'; } }; static_cast<Printer const&>(adaptor).print(name); } 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", s1); print("s2", s2); s1.swap(s2); print("s1", s1); print("s2", s2); }
输出:
s1 [4]: 4 3 2 1 s2 [5]: Ǝ D Ɔ B Ɐ s1 [5]: Ǝ D Ɔ B Ɐ s2 [4]: 4 3 2 1
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用范围 | 发布时行为 | 正确行为 |
|---|---|---|---|
| LWG 2456 | C++11 |
noexcept
规范格式错误
|
已修复可用 |
参见
|
(C++11)
|
特化
std::swap
算法
(函数模板) |